理解 Python 的 `属性` 和 `__init__`

Understanding Python's `property` and `__init__`

考虑以下 class:

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')

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

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