Setting a variable python class - function
本问题已经有最佳答案,请猛点这里访问。
有没有一个函数,我可以写,但作为一个函数?
1 2 3 4 5 6 7 | class foo: def __init__(self,x): self.x = x; asd = foo(2); asd.x = 5; print(asd.x); |
但像:
1 2 3 4 5 6 7 8 9 10 | class foo: def __init__(self,x): self.x = x; def someFunction(self,string,value): if(string == 'x'): self.x = value; print("worked"); asd = foo(2); asd.x = 3; #and"worked" will be printed? |
我试过"设定"和"设定"但我运气不好;
在设置类变量时是否有方法调用函数?asd.x=3;调用函数?
使用属性。当您试图访问属性
1 2 3 4 5 6 7 8 9 10 11 12 13 | class foo: @property def x(self): return self._x @x.setter def x(self, value): self._x = value print("worked") def __init__(self, x): self._x = x |
如果需要getter和setter方法的更明确名称,可以跳过decorator语法:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class foo(object): def __init__(self, x): self._x = x def _get_x(self): return self._x def _set_x(self, value): self._x = value print("worked") x = property(_get_x, _set_x) |
对于要处理自身属性设置的对象,请使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Beer(object): def __init__(self, adj): self.adj = adj def __setattr__(self, key, value): print '\tSET',key,value object.__setattr__(self, key, value) # new style (don't use __dict__) b = Beer('tasty') print 'BEFORE',b.adj b.adj = 'warm' print 'AFTER',b.adj print b.__dict__ |
输出
1 2 3 4 5 | SET adj tasty BEFORE tasty SET adj warm AFTER warm {'adj': 'warm'} |