getattr and @property

来源:互联网 发布:淘宝卖家多长时间回款 编辑:程序博客网 时间:2024/06/03 14:22

1. property的作用

    负责把一个方法变成属性调用

2. getattr(object, name[,default])

获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。
需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,
可以在后面添加一对括号。


>>> class test():
...     name="Wang"
...    
...     def run(self):
...             return "Hello"
...

>>>t=test()

>>> t.run()
'Hello'

>>> t.run
<bound method test.run of <__main__.test instance at 0x105a64f80>>

>>> getattr(t, "run")()
'Hello'
>>> getattr(t, "run")
<bound method test.run of <__main__.test instance at 0x105a64fc8>>


如果使用@property

>>> class test():
...     name="Wang"
...     @property
...     def run(self):
...             return "Hello"
...
>>> t=test()

>>> t.run()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> t.run
'Hello'

>>> getattr(t, "run")()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

>>> getattr(t, "run")
'Hello'
0 0
原创粉丝点击