在Python 3中,可以通过以下几种方式从父类中的子类获取属性:
super()
:super()
函数用于调用父类的方法,通过调用父类的__init__()
方法来获取父类的属性。例如:class Parent:
def __init__(self):
self.parent_attr = "Parent Attribute"
class Child(Parent):
def __init__(self):
super().__init__() # 调用父类的__init__()方法
self.child_attr = "Child Attribute"
child = Child()
print(child.parent_attr) # 输出:Parent Attribute
class Parent:
parent_attr = "Parent Attribute"
class Child(Parent):
child_attr = "Child Attribute"
child = Child()
print(child.parent_attr) # 输出:Parent Attribute
getattr()
函数:getattr()
函数用于获取对象的属性值,可以通过传入父类和属性名来获取父类的属性。例如:class Parent:
parent_attr = "Parent Attribute"
class Child(Parent):
child_attr = "Child Attribute"
child = Child()
print(getattr(child.__class__.__bases__[0], 'parent_attr')) # 输出:Parent Attribute
以上是从父类中的子类获取属性的几种常见方式。根据具体的情况选择适合的方式来获取属性值。
领取专属 10元无门槛券
手把手带您无忧上云