unbound method & bound method

来源:互联网 发布:php 子类使用父类属性 编辑:程序博客网 时间:2024/04/24 09:51

>>> class Test:
 def __init__(self):
  self.data = "test"
  
 def func(self):
  print self.data

  
>>> f = getattr(Test,func)

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in -toplevel-
    f = getattr(Test,func)
NameError: name 'func' is not defined
>>> f = getattr(Test,"func")
>>> f
<unbound method Test.func>
>>> f()

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in -toplevel-
    f()
TypeError: unbound method func() must be called with Test instance as first argument (got nothing instead)
>>> f(Test())
test
>>> f = getattr(Test(),"func")
>>> f
<bound method Test.func of <__main__.Test instance at 0x00D57968>>
>>> f()
test