子类能否在 Python 中访问其超类的属性?
Can a subclass access attributes from its superclass in Python?
在Python中,子类是否可以访问其超类的属性?下面是一个简短的示例代码,我想使用它。
class A:
def __init__(self, some_value):
self.some_property_A = some_value
class B:
def __init__(self):
self.some_property_B = 0
if some_property_A == 1: # <-------- How can I make this line work?
self.some_property_B = 1
提前感谢您的帮助。
你的 Class B 不是你的子类。
示例如下:
# superclass
class Person():
def __init__(self, per_name, per_age):
self.name = per_name
self.age = per_age
# subclass
class Employee(Person):
def __init__(self, emp_name, emp_age, emp_salary):
self.salary = emp_salary
Person.__init__(self, emp_name, emp_age)
emp = Employee("John", 20, 8000) # creating object of superclass
print("name:", emp.name, "age:", emp.age, "salary:", emp.salary)
这就是你如何使用超类的变量。
如需更多信息,请访问:
在Python中,子类是否可以访问其超类的属性?下面是一个简短的示例代码,我想使用它。
class A:
def __init__(self, some_value):
self.some_property_A = some_value
class B:
def __init__(self):
self.some_property_B = 0
if some_property_A == 1: # <-------- How can I make this line work?
self.some_property_B = 1
提前感谢您的帮助。
你的 Class B 不是你的子类。
示例如下:
# superclass
class Person():
def __init__(self, per_name, per_age):
self.name = per_name
self.age = per_age
# subclass
class Employee(Person):
def __init__(self, emp_name, emp_age, emp_salary):
self.salary = emp_salary
Person.__init__(self, emp_name, emp_age)
emp = Employee("John", 20, 8000) # creating object of superclass
print("name:", emp.name, "age:", emp.age, "salary:", emp.salary)
这就是你如何使用超类的变量。 如需更多信息,请访问: