学习目标:
正确区分类的初始化与回调
有关类的初始化
class A():
def __init__(self):
print('Hello, world!')
A()
有关类的调用
class A():
def __call__(self):
print('hello,world!!!!!!!!!!!!!!')
a = A()
a()
这就是__init__与__call__在用法上的区别!
关于二者在编程中具体应用
示例一
class A():
def __init__(self):
print('hello,world!')
def __call__(self):
print('hello,world!!!!!!!!!!!!!')
a = A()
a()
示例二
class A():
def __init__(self, init_age):
print('我年龄是:', init_age)
self.age = init_age
def __call__(self, added_age):
res = self.forward(added_age) #调用forward函数
return res
def forward(self, input_):
print('forward 函数被调用了')
return input_ + self.age
print('对象初始化………………')
a = A(16)
input_param = a(2)
print("我现在的年龄永远是:", input_param)
示例三
class Animal():
def __init__(self,name):
self.name = name
def greet(self):
print('animal is {}'.format(self.name))
class Cat(Animal):
def greet(self):
super(Cat, self).greet()
print("It's name is wangwang")
a=Cat('cat')
a.greet()