我想问一下Python Property,我正在写下面的代码...
任何人都可以解释我的代码的输出并以简单的方式解释什么是属性以及我们应该何时使用它?
class C(object):
def __init__(self):
self.x = 'sulthan'
self.y = 'ahnaf'
@property
def name(self):
print self.x
print self.y
现在当我运行代码时:
>>> c = C()
>>> c.name
sulthan
ahnaf
sulthan
ahnaf
为什么打印两次?很抱歉这个问题,我只是想了解 python OOP 的菜鸟...
最佳答案
这似乎是 ipython 的问题,如果您使用 python 提示它显示正确的输出(单次)
[avasal@avasal]$ python
Python 2.7 (r27:82500, Sep 16 2010, 18:02:00)
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class C(object):
... def __init__(self):
... self.x = 'sulthan'
... self.y = 'ahnaf'
... @property
... def name(self):
... print self.x
... print self.y
...
>>> c1 = C()
>>> c1.name
sulthan
ahnaf
>>>
[avasal@avasal]$ ipython
Python 2.7 (r27:82500, Sep 16 2010, 18:02:00)
Type "copyright", "credits" or "license" for more information.
IPython 0.10.2 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: class C(object):
...: def __init__(self):
...: self.x = 'sulthan'
...: self.y = 'ahnaf'
...: @property
...: def name(self):
...: print self.x
...: print self.y
...:
In [2]: c1 = C()
In [3]: c1.name
sulthan
ahnaf
sulthan
ahnaf
In [4]:
关于python - 理解 Python 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9288868/