天天看点

python面向对象高级编程_python Class:面向对象高级编程 __call__& callable()

python Class:面向对象高级编程 __call__& callable()

发布时间:2020-04-08 10:15:58

来源:51CTO

阅读:762

官网解释:

3.4.5. Emulating callable objectsobject.__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, ...).

看得懂,但看不明白。。。。。真是硬伤。。。。

这两天发文老是被审核,想不通,是不是我把廖某的全名打出来有人不爽????

为了更好理解,引用廖某的__call__程序与自己的__repr__ / __str__程序做比较:#廖:__call__此程序的结果是输出输入的name

class Student1(object):

def __init__(self, name):

self.name = name

def __call__(self):

print('My name is %s.' % self.name)

h = Student1('MumU')

print 'liao:', h

#我:__repr__ / __str__ 此程序的结果也是输出输入的name

class Student2(object):

def __init__(self, name):

self.name = name

def __str__(self):

return 'Student2 name:%s'%self.name

__repr__ = __str__

l = Student2('U')

print 'me:', l

运行结果:liao: <__main__.Student1 object at 0x7f5fea3108d0>

me: Student2 name:U

嗯,为啥Student1会输出这样呢???

再换一个试法:程序Class都没改,只是输出语句改了(标记:####)#廖:__call__此程序的结果是输出输入的name

class Student1(object):

def __init__(self, name):

self.name = name

def __call__(self):

print('My name is %s.' % self.name)

print Student1('MumU') ####

#我:__repr__ / __str__ 此程序的结果也是输出输入的name

class Student2(object):

def __init__(self, name):

self.name = name

def __str__(self):

return 'Student2 name:%s'%self.name

__repr__ = __str__

print Student2('U') ####

运行结果:liao: <__main__.Student1 object at 0x7f13dc36b8d0>

me: Student2 name:U

嗯,还是一样,想想也是,因为这输出写法和之前的是等价的。。。。于是我就想,如果__call__是调用自己的函数的话,那么要用函数就得。。。在末尾加()号?!

再试:只改了廖的输出语句(标记:####)#廖:__call__此程序的结果是输出输入的name

class Student1(object):

def __init__(self, name):

self.name = name

def __call__(self):

print('My name is %s.' % self.name)

print Student1('MumU')() ####

#我:__repr__ / __str__ 此程序的结果也是输出输入的name

class Student2(object):

def __init__(self, name):

self.name = name

def __str__(self):

return 'Student2 name:%s'%self.name

__repr__ = __str__

print Student2('U')

运行结果:liao: My name is MumU.

None

me: Student2 name:U

敲你吗,还真是函数。。。。

敲了这么多,蒙了也正常,换个普通的就懂了。class Animal(object):

def __init__(self, name):

self.name = name

def run(self):

print '%s is running'%self.name

dog = Animal('dog')

print '当你要查看class的属性name时:', dog.name

print '当你要查看class的方法(函数)时:', dog.run()

运行结果:当你要查看class的属性name时: dog

当你要查看class的方法(函数)时: dog is running

None

查看属性是不加()号的, 使用方法(函数)时才需要。

至于为什么运行末尾都有个None??

Because,

dog.run()已经执行了一次print 了,def run(self):

print '%s is running'%self.name

而print '当你要查看class的方法(函数)时:', dog.run()

再次执行了一次,所以这个print 就只能输出None了。

我真是太聪明了,哈哈哈哈哈

callable: 查看对象是否可调用,即是否为函数print 'Student1 可调用??', callable(Student1('MumU'))

print 'Student2 可调用??', callable(Student2('U'))

运行结果:Student1 可调用?? True

Student2 可调用?? False