理解Python中的属性
发布时间:2020-12-20 11:23:36 所属栏目:Python 来源:网络整理
导读:我想问一下 Python Property,我正在编写下面的代码…… 任何人都可以解释我的代码的输出,并以简单的方式解释什么是属性以及何时应该使用它? class C(object): def __init__(self): self.x = 'sulthan' self.y = 'ahnaf' @property def name(self): print se
我想问一下
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,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]: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |