在 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
感謝您提前提供幫助。
uj5u.com熱心網友回復:
您的 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)
這就是你可以如何使用超類的變數。欲了解更多資訊,請訪問:
https://www.codesdope.com/course/python-subclass-of-a-class/#:~:text=All the attributes and methods,and methods of the superclass。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/442674.html
下一篇:在類內的另一個函式中使用變數
