前面说了descriptor,这个东西其实和Java的setter,getter有点像。但这个descriptor和上文中我们开始提到的函数方法这些东西有什么关系呢?
所有的函数都可以是descriptor,因为它有__get__方法。
>>> def hello():
pass
>>> dir(hello)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__
', '__getattribute__',
'__hash__', '__init__', '__module__', '__name__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure',
'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
>>>
注意,函数对象没有__set__和__del__方法,所以它是个non-data descriptor.
方法其实也是函数,如下:
>>> class T(object):
def hello(self):
pass
>>> T.__dict__['hello']
>>>
或者,我们可以把方法看成特殊的函数,只是它们存在于类 中,获取函数属性时,返回的不是函数本身(比如上面的
>>> T.hello 获取T的hello属性,根据查找策略,从T的__dict__中找到了,找到的是
>>> f = T.__dict__['hello'] #直接从T的__dict__中获取hello,不会执行查找策略,直接返回了
>>> f
>>> t = T()
>>> t.hello #从实例获取属性,返回的是调用
>>>
为了证实我们上面的说法,在继续下面的代码(f还是上面的
>>> f.__get__(None, T)
>>> f.__get__(t, T)
好极了!
总结一下:
1.所有的函数都有__get__方法
2.当函数位于类的__dict__中时,这个函数可以认为是个方法,通过类或实例获取该函数时,返回的不是函数本身,而是它的__get__方法返回值。
我承认我可能误导你认为方法就是函数,是特殊的函数。其实方法和函数还是有区别的,准确的说:方法就是方法,函数就是函数。
>>> type(f)
>>> type(t.hello)
>>> type(T.hello)
>>>
函数是function类型的,method是instancemethod(这是普通的实例方法,后面会提到classmethod和staticmethod)。
关于unbound method和bound method,再多说两句。在c实现中,它们是同一个对象(它们都是instancemethod类型的),我们先看看它们里面到底是什么
>>> dir(t.hello)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', 'im_class', 'im_func', 'im_self']
__call__说明它们是个可调用对象,而且我们还可以猜测,这个__call__的实现应该大致是:转调另外一个函数(我们期望的哪个,比如上面的hello),并以对象作为第一参数。
要 注意的是im_class,im_func,im_self。这几个东西我们并不陌生,在t.hello里,它们分别代表T,hello(这里是存储在 T.__dict__里的函数hello)和t。有了这些我们可以大致想象如何纯Python实现一个instancemethod了:)。
其实还有几个内建函数都和descriptor有关,下面简单说说。
classmethod
classmethod能将一个函数转换成类方法,类方法的第一个隐含参数是类本身 (普通方法的第一个隐含参数是实例本身),类方法即可从类调用,也可以从实例调用(普通方法只能从实例调用)。
>>> class T(object):
def hello(cls):
print 'hello', cls
hello = classmethod(hello) #两个作用:把hello装换成类方法,同时隐藏作为普通方法的hello
>>> t = T()
>>> t.hello()
hello
>>> T.hello()
hello
>>>
注意:classmethod是个类,不是函数。classmethod类有__get__方法,所以,上面的t.hello和T.hello获得实际上是classmethod的__get__方法返回值
>>> t.hello
>>> type(t.hello)
>>> T.hello
>>> type(T.hello)
>>>
从 上面可以看出,t.hello和T.hello是instancemethod类型的,而且是绑定在T上的。也就是说classmethod的 __get__方法返回了一个instancemethod对象。从前面对instancemethod的分析上,我们应该可以推断:t.hello的 im_self是T,im_class是type(T是type的实例),im_func是函数hello
>>> t.hello.im_self
>>> t.hello.im_class
>>> t.hello.im_func
>>>
完全一致!所以实现一个纯Python的classmethod也不难:)
staticmethod
staticmethod能将一个函数转换成静态方法,静态方法没有隐含的第一个参数。
class T(object):
def hello():
print 'hello'
hello = staticmethod(hello)
>>> T.hello() #没有隐含的第一个参数
hello
>>> T.hello
>>>
T.hello直接返回了一个函数。猜想staticmethod类的__get__方法应该是直接返回了对象本身。
还有一个property,和上面两个差不多,它是个data descriptor。

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools