调用方法和访问属性之间的区别

D00*_*07a 6 python oop

我是Python的新手,我使用的是Python 3.3.1.

class Parent: # define parent class 
    parentAttr = 100
    age = 55

    def __init__(self): 
        print ("Calling parent constructor") 

    def setAttr(self, attr): 
        Parent.parentAttr = attr 

class Child(Parent):
    def childMethod(self):
        print ('Calling child method')
Run Code Online (Sandbox Code Playgroud)

现在我要创造

c=child
c.[here every thing will appear methods and attr (age,setAttr)]
Run Code Online (Sandbox Code Playgroud)

我怎样才能区分方法和属性?我的意思是,我什么时候使用c.SetAtrr(Argument), c.SetAtrr=value

Mar*_*ers 11

方法也是属性.它们恰好是可调用的对象.

您可以使用以下callable()函数检测对象是否可调用:

>>> def foo(): pass
...
>>> callable(foo)
True
>>> callable(1)
False
Run Code Online (Sandbox Code Playgroud)

调用方法时,查找属性(getattr()操作),然后调用结果:

c.setAttr(newvalue)
Run Code Online (Sandbox Code Playgroud)

是两步; 找到属性(在这种情况下查找类上的属性,并将其视为描述符),然后调用结果对象,即方法.

当你分配到一个属性,你重新绑定该名称为新值:

c.setAttr = 'something else'
Run Code Online (Sandbox Code Playgroud)

将是一项setattr()行动.

如果你想拦截获取和你的类的实例设置属性,您可以提供的访问属性挂钩,__getattr__,__setattr____delattr__.

如果要向实例添加方法,则必须将该函数视为描述符对象,从而生成方法对象:

>>> class Foo: pass
... 
>>> foo = Foo()  # instance
>>> def bar(self): pass
... 
>>> bar
<function bar at 0x10b85a320>
>>> bar.__get__(foo, Foo)
<bound method Foo.bar of <__main__.Foo instance at 0x10b85b830>>
Run Code Online (Sandbox Code Playgroud)

function.__get__()给定实例和类时,返回值是绑定方法.调用该方法将调用self绑定到实例的底层函数.

说到描述符,property()函数也会返回一个描述符,从而可以使函数表现得像属性一样; 他们可以拦截getattr(),setattr()delattr()操作仅针对该属性,并把它变成一个函数调用:

>>> class Foo:
...     @property
...     def bar(self):
...         return "Hello World!"
... 
>>> foo = Foo()
>>> foo.bar
"Hello World!"
Run Code Online (Sandbox Code Playgroud)

访问.bar调用bar属性get钩子,然后调用原始bar方法.

在几乎所有情况下,您都不需要该callable()功能; 您记录您的API,并提供方法和属性,API的用户将在不测试每个属性的情况下找出它以查看它是否可调用.使用属性,您可以灵活地提供在任何情况下都是真正可调用的属性.