理解Python中的属性

我想问一下
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

为什么要打印2次?对不起,这个问题,我只是想要了解python OOP的noob …

最佳答案 这似乎是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]:
点赞