学习目标:
正确区分类的初始化与回调
有关类的初始化
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()

本文详细介绍了Python中类的__init__和__call__方法的区别和用法,通过实例展示了它们在类初始化和对象调用过程中的作用。示例一展示了__init__和__call__的基本使用,示例二进一步解释了如何在__call__中调用其他方法,而示例三则涉及类的继承和方法覆盖。理解这两个方法对于掌握Python面向对象编程至关重要。
4130

被折叠的 条评论
为什么被折叠?



