在Python中,__str__
方法是一个特殊的方法,用于定义对象的字符串表示形式。当我们使用print
函数或者将对象转换为字符串时,会自动调用__str__
方法。
在__str__
方法中调用super()
函数,可以实现在子类中重写父类的__str__
方法,并在子类中添加额外的逻辑。super()
函数返回一个代理对象,通过该对象可以调用父类的方法。
下面是一个示例:
class Parent:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Parent: {self.name}"
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
def __str__(self):
parent_str = super().__str__()
return f"Child: {self.name}, Age: {self.age}\n{parent_str}"
child = Child("Alice", 10)
print(child)
输出结果为:
Child: Alice, Age: 10
Parent: Alice
在上面的示例中,Child
类继承自Parent
类,并重写了__str__
方法。在Child
类的__str__
方法中,通过super().__str__()
调用了父类Parent
的__str__
方法,并将其结果添加到子类的字符串表示中。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅为示例,具体产品和服务选择应根据实际需求进行评估和选择。
云+社区技术沙龙[第11期]
2024腾讯全球数字生态大会
企业创新在线学堂
企业创新在线学堂
企业创新在线学堂
企业创新在线学堂
云+社区沙龙online第6期[开源之道]
领取专属 10元无门槛券
手把手带您无忧上云