在python中定义属性
我有一门课是这样的:在python中定义属性,python,Python,我有一门课是这样的: class MyItem: def __init__(self): self.person = None self.place = None self.thing = None # property 但是,我还想为其中一个属性定义一个属性,例如: @property def thing(self): return self.person + self.place 换句话说,我想让我
class MyItem:
def __init__(self):
self.person = None
self.place = None
self.thing = None # property
但是,我还想为其中一个属性定义一个属性,例如:
@property
def thing(self):
return self.person + self.place
换句话说,我想让我的初始化显示我所有的变量,所以它是显式的,但我想用class属性“覆盖”其中一个属性。我该怎么做
作为我目前拥有的一个例子:
class MyItem:
def __init__(self):
self.person = None
self.place = None
self.thing = None # property
@property
def thing(self):
return self.person + self.place
m=MyItem()
m.person='A'
m.place='B'
print m.thing
>>> None
也许这不是你想要的答案,但我的建议是: 不要在多个位置定义
MyItem.thing
。
这会让人困惑,从长远来看可能会让你心痛。还有短期
问题是,MyItem.\uuuu init\uuuu()
不是文档,它只是定义实例化是如何发生的。文档就是文档,不幸的是,有时候写文档有点麻烦。查看和/或项目,了解这些工具如何根据您的类、属性、方法等为您编写文档
我会这样做:
class MyItem:
"""
Defines an item.
Attributes
----------
person: A person.
place: A place.
Properties
----------
thing: A thing, the sum of person and place.
Methods
-------
There aren't any, but there will be!
"""
def __init__(self, person=None, place=None):
self.person = person
self.place = place
@property
def thing(self):
"""
Property of MyItem instance. The sum of person and place,
if both of those things exist.
Returns
-------
str. The sum of the person and place attributes.
"""
if (self.person is not None) and (self.place is not None):
return self.person + self.place
else:
return None
m = MyItem('A', 'B')
print(m.thing)
这将返回:
'AB'
我也会尽快开始使用Python 3。这里有两件事不对。首先,您编写的代码允许通过实例属性对属性进行隐藏,因为您在Python 2上并且没有从对象继承,描述符协议需要新样式的类才能正常工作。因此,请注意我们这样做时会发生什么:
class MyItem(object):
def __init__(self):
self.person = None
self.place = None
self.thing = None # property
@property
def thing(self):
return self.person + self.place
m=MyItem()
m.person='A'
m.place='B'
print m.thing
输出应为:
Traceback (most recent call last):
File "test.py", line 10, in <module>
m=MyItem()
File "test.py", line 5, in __init__
self.thing = None # property
AttributeError: can't set attribute
它现在输出:
AB
但是,我认为这是一个失败的例子,可能会导致头痛。我强烈建议不要这样做,但这是可能的。它可以在
\uuu init\uuu
文档字符串中以英语出现,或者作为self.place
下面的注释出现,那么到底是什么阻止了你?当您尝试上述操作时,是否有任何错误?你研究了什么?@juanpa.arrivillaga当我尝试上述方法时,它使用的是\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuu>中的属性,而不是属性。如果它应该是属性,为什么要将它赋值给self.thing
?@FI Info它真的能保证答案吗?这如何解决OP希望在\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法中显示有属性的问题呢?嗯。。。。它没有,那一点没有被吸收。但是现在,我不明白这个要求。出于某种原因,他认为\uuuu init\uuu
方法应该是类属性的自文档。好的,我试着反映一下我对这个想法的看法。干杯。@kwinkunks您将在文档中的何处/如何定义类变量和方法?或者您不这样做,只是将这些文档放在相应的方法中?您可以让setter检查值是否为None
,否则会抛出一个错误。@Barmar这是可能的。尽管如此,对我来说似乎只是一个坏主意。好吧,最初的目标是错误的,没有好的解决方案,只有更少的坏方案。
AB