如何从内部调用Python(v2.7)setter属性__init__
?我写了以下课程,但我不知道如何更改它以使其正常工作。我有一个AttributeError: 'test' object has no attribute '_x'
例外。这里也有一些类似的问题,但到目前为止找不到答案。这个想法是当调用初始化程序进行一些处理/切片并将结果分配给属性时
class test(object):
def __init__(self, a,b):
self._x = self.x(a,b)
@property
def x(self):
return self._x
@x.setter
def x(self, a, b):
self._x = "Get this from {} and make a dataframe like {}".format(a,b)
self.x
是属性,因此您可以直接将其分配给它,就像使用常规属性一样:
def __init__(self, a, b):
self.x = (a, b)
但是,设置者总是会得到一个对象。在上述情况下,将其传递给元组;您可以打开它的包装:
@x.setter
def x(self, value):
a, b = value
self._x = "Get this from {} and make a dataframe like {}".format(a,b)
注意value
论点;这是将分配传递给设置器的结果。
演示:
>>> class test(object):
... def __init__(self, a, b):
... self.x = (a, b)
... @property
... def x(self):
... return self._x
... @x.setter
... def x(self, value):
... a, b = value
... self._x = "Get this from {} and make a dataframe like {}".format(a,b)
...
>>> t = test(42, 'foo')
>>> t.x
'Get this from 42 and make a dataframe like foo'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句