python里面其实有一些很方便强大的特性,但是可能一般常见的其他语言里没有对应的特性。导致很多其他语言转python的,或者python新手都不知道这些特性,甚至有时候一些对python比较了解的开发者也并不知道这些。下面给大家介绍一下python里面具有强大魔力的几个特性。
魔术方法(Magic Method)
python里的魔术方法类似于某些开发场景下使用的回调函数或者叫钩子函数。原理其实也简单,就是python预定义了很多方法,在不同的情况下执行这些方法,你可以自己定义相应的方法覆盖默认方法,这样在对应的情况下会执行你自己定义的方法。
比如我们常用dir来查看对象里的成员:
>>> class T:
... def print(self):
... print(self)
...
>>> t=T()
>>> dir(t)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'print']
>>> class T:
... def print(self):
... print(self)
... def __dir__(self):
... return ["hello","world"]
...
>>> t=T()
>>> dir(t)
['hello', 'world']
可以看到,默认dir返回的是对象所有成员,但定义__dir__方法之后,dir返回的是我们定义的__dir__返回的内容。这就是因为dir在调用的时候,默认会优先调用对象的__dir__方法,如果没有再返回默认的对象可用属性。
python里面预定义的魔术方法很多,下面列出常用的魔术方法:
__init__ 类实例初始化的时候触发,非常常用
__del__ 对象被清理的时候触发
__repr__ print对象的时候调用
__str___ str()对象的时候调用
__getattr__(self, name) 访问对象不存在属性时候触发
__getattribute__(self, name) 同上,但优先于__getattr__触发
__setattr__(self, name, value) 设置对象属性的时候触发,注意和__getattr__触发条件不一样
__delattr__(self, name) 删除对象属性的时候触发,类似 del t.xxx
下面就是喜闻乐见的操作符重载的系列方法,就不一一注释了,主要是加减乘除和比较
__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__matmul__(self, other)
__truediv__(self, other)
__floordiv__(self, other)
__mod__(self, other)
__divmod__(self, other)
__pow__(self, other[, modulo])
__lshift__(self, other)
__rshift__(self, other)
__and__(self, other)
__xor__(self, other)
__or__(self, other)
__lt__(self, other)
__le__(self, other)
__eq__(self, other)
__ne__(self, other)
__gt__(self, other)
__ge__(self, other)
元编程(Meta programming)
python的优越性之一,就在于元编程了。元编程是什么呢?其他语言开发者可能接触比较少,元编程就是可以在编程中操作类或者对象本身。简单说,就是可以动态生成类或者修改类的一种编程方式。
主要有下面几种形式
动态生成类
假设一个需求场景,你需要实现一个orm,里面为了方便使用,需要根据表结构动态生成一个类。这在很多语言里是基本无法实现的,但是python里恰好有这种魔法。
记得我们常用的type()么?就是用来查看对象类型的那个,这个方法同时也可以用来构造类,实际上,python里定义新类,用的就是type()。牢记一点,在python里,类也是一种对象,当然可以动态创建了。注意一点,python里面,除了type,所有类的父类是object,而object类型是type。
>>> def p(self):
... print(self)
...
>>> T=type("T",(object,),dict(p=p))
>>> T
<class '__main__.T'>
>>> t1=T()
>>> dir(t1)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'p']
>>> t1.p()
<__main__.T object at 0x000002A649D90EF0>
可以看到,type的第三个参数是定义的类的属性。属性列表里,方法的第一个参数就是类实例本身,这也解释了为啥我们在python里定义类方法的时候,第一个参数都是self。
动态添加类方法
python里动态增加类方法还是很简单的。使用python内置的setattr方法,可以设置一个方法成为类属性。当然最简单的是直接用属性赋值的方式。
>>> def p1(self):
... print(self)
...
>>> t1.p1=p1
>>> dir(t1)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'p', 'p1']
>>> t1.p1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: p1() missing 1 required positional argument: 'self'
>>> dir(T)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'p']
>>> def p1(self):
... print(self)
...
>>> T.p1=p1
>>> t1=T()
>>> dir(t1)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'p', 'p1']
>>> t1.p1()
<__main__.T object at 0x000002A649D920B8>
注意上面的例子,增加的方法是加到类上,而不是实例上。还有一种办法,可以定义类的__getattr__方法也可以实现自定义方法,但是这种方式无法在类属性里看到这些属性。
修饰器
修饰器应该是python里非常常见的特性了,和设计模式里的修饰器模式有点类似。简言之就是定义类或者方法的时候,加上修饰器之后,实际得到的类或者方法,会变成以定义的类或者方法为参数调用修饰器方法后返回的类或者方法。
#官方的例子
@f1(arg)
@f2
class Foo: pass
#大致等价于
class Foo: pass
Foo = f1(arg)(f2(Foo))
举个例子
>>> def change(x):
... return T
...
>>> @change
... class X:
... pass
...
>>> X
<class '__main__.T'>
这是一个极端的例子,直接替换定义的类。可以看到,定义的类本来是X,因为使用的修饰器返回的是我们之前定义的T,所以实际定义的X就是T。
写在结尾
其实python里面这些特性,也许在其他语言里也有,但在最常见的语言里,python的这些特性还是算相对完整的。用好这些语言特性,能让语言表达能力大幅提升,而且同时又很简洁。
网友评论