理解Python的“属性”和“__init__”

时间:2015-02-21 01:37:53

标签: python object built-in

考虑以下课程:

class HotDog():

    def __init__(self):
        self.v_th = 10

    def _new_property(obj_hierarchy, attr_name):
        def set(self, value):
            obj = reduce(getattr, [self] + obj_hierarchy.split('.'))
            setattr(obj, attr_name, value)
        def get(self):
            obj = reduce(getattr, [self] + obj_hierarchy.split('.'))
            return getattr(obj, attr_name)
        return property(fset=set, fget=get)

    x.vthresh = 77

    v_th = _new_property('x', 'vthresh')

如果我要创建此类的实例 - 比如x = HotDog() - 我会找到x.v_th == 10。为什么会这样?在我看来,该值最初应设置为10,但在self.v_th被重新定义为_new_property('x', 'vthresh')时会被覆盖。 __init__初始化后,x中的代码是否在此其他代码之后执行了?

1 个答案:

答案 0 :(得分:3)

创建类时,将执行类范围内的所有代码。创建对象时会调用__init__()方法。因此,所有类范围代码都在__init__()方法之前运行。

相关问题