Python 中的一切都是对象,甚至是函数和方法。这样的事实hasattr()需要的对象是没有什么特别的,所以做str()和input()和sum()。
方法是通过作为属性访问对象而绑定到对象的函数;所以"foo bar".split给你绑定str.split方法:
>>> "foo bar".split
<built-in method split of str object at 0x7f84bef6a730>
Run Code Online (Sandbox Code Playgroud)
这个恰好是“内置的”,因为它是作为 Python 运行时的一部分实现的,但它与用 Python 编写的类上的函数没有什么不同。
调用它返回应用到它绑定到的字符串的方法的结果:
>>> method = "foo bar".split
>>> method()
['foo', 'bar']
Run Code Online (Sandbox Code Playgroud)
我也可以直接使用它,未绑定:
>>> str.split("spam ham")
['spam', 'ham']
Run Code Online (Sandbox Code Playgroud)
hasattr()不受约束。这是一个函数。即使您尝试过* ,也无法像使用 Python 函数那样绑定它。
添加到类中的 Python 函数在您作为类实例的属性访问它们时自动成为方法:
>>> class KnightsWhoSayNi:
... pass
...
>>> def speak(self): return "Ni!"
...
>>> speak
<function speak at 0x10fe65f28>
>>> knight = KnightsWhoSayNi()
>>> hasattr(knight, "speak") # using that function you mentioned!
False
>>> KnightsWhoSayNi.speak = speak # adding the function to the class
>>> knight.speak # now it exists! As a method...
<bound method speak of <__main__.KnightsWhoSayNi object at 0x10fe71080>>
>>> knight.speak()
'Ni!'
Run Code Online (Sandbox Code Playgroud)
请注意 howspeak()给出了一个名为 的参数self,但我不必传入它。因为该方法绑定到类的特定实例,所以会自动处理。传入的第一个参数是实例。名称甚至无关紧要,但这self是惯例,最好坚持下去。
作为练习,您可以自己尝试上面的示例。然后尝试添加hasattr到类中。你会发现你可以使用t use it like a method, it won't become bound via Knight.hasattr`,实例不会作为第一个参数传入,你仍然需要传入两个参数才能让它工作。
如果您想深入了解,可以在Python 描述符 HOW-TO 中了解绑定的工作原理。如果觉得这一步太大,请不要担心,这已经相当先进了。
*抢占不采摘:您可以使用或模拟绑定,但这不是完全相同的事情。functools.partial()functools.partialmethod()
| 归档时间: |
|
| 查看次数: |
225 次 |
| 最近记录: |