python中的 __xxx__ 方法
1 __class__
instance.__class__
The class to which a class instance belongs
def foo(): pass class A(object): pass s = 'abc' l = [1,2,3] t = (1,2,3) d = {'a':1} print('foo',foo.__class__) print('foo',foo.__class__.__class__) print('A',A.__class__) print('A',A.__class__.__class__) print('s',s.__class__) print('s',s.__class__.__class__) print('l',l.__class__) print('l',l.__class__.__class__) print('t',t.__class__) print('t',t.__class__.__class__) print('d',d.__class__) print('d',d.__class__.__class__)
输出:
foo <class 'function'> foo <class 'type'> A <class 'type'> A <class 'type'> s <class 'str'> s <class 'type'> l <class 'list'> l <class 'type'> t <class 'tuple'> t <class 'type'> d <class 'dict'> d <class 'type'>
2 __name__
definition.__name__
The name of the class, function, method, descriptor, or generator instance.
def foo(): pass class A(object): pass s = 'abc' l = [1,2,3] t = (1,2,3) d = {'a':1} print(foo.__name__) print(foo.__class__.__name__) print(foo.__class__.__class__.__name__) print(A.__name__) print(A.__class__.__name__) print(A.__class__.__class__.__name__)
输出:
foo
function
type
A
type
type
3 __call__
object.__call__(self,[ args ** ])
Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...)
is a shorthand for x.__call__(arg1, arg2, ...)
.
Python中的函数是一级对象。这意味着Python中的函数的引用可以作为输入传递到其他的函数/方法中,并在其中被执行。
而Python中类的实例(对象)可以被当做函数对待。也就是说,我们可以将它们作为输入传递到其他的函数/方法中并调用他们,正如我们调用一个正常的函数那样。而类中__call__()
函数的意义正在于此。为了将一个类实例当做函数调用,我们需要在类中实现__call__()
方法。也就是我们要在类中实现如下方法:def __call__(self, *args)
。这个方法接受一定数量的变量作为输入。
假设x是X类的一个实例。那么调用x.__call__(1,2)
等同于调用x(1,2)
。这个实例本身在这里相当于一个函数。
class A(object): def __init__(self,name,age): self.name = name self.age = age def __call__(self): print('{}年龄{}'.format(self.name,self.age)) a = A('zuo',18) a() class B(object): def __init__(self): pass def __call__(self,a,b): self.a = a self.b = b print('{}*{}={}'.format(a,b,a*b)) b = B() b(4,5) b.__call__(4,5)