Reputation: 10761
Consider the following 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')
If I were to create an instance of this class -- say, x = HotDog()
-- I would find that x.v_th == 10
. Why is this the case? It seems to me that the value should be set to 10 initially, but then overwritten when self.v_th
is rededfined to be _new_property('x', 'vthresh')
. Is the code in __init__
executed after this other code when x
is initialized?
Upvotes: 1
Views: 33
Reputation: 798814
All code at class scope is executed when the class is created. The __init__()
method is called when the object is created. Therefore all class scope code is run before the __init__()
method is.
Upvotes: 3