我正在使用 python 3.4,我是面向对象编程的新手,想要访问我的子类中的父类成员。但它无法访问。谁能帮我摆脱这个?
# Base class members can be accessed in
# derived class using base class name.
# Parent or super class
class Company:
def BasicInfo(self):
self.CompanyName = "ABC Solutions"
self.Address = "XYZ"
# Inherited or child class
class Employee(Company):
# constructor
def __init__(self, Name):
print("Employee Name:", Name)
print("Company Name:", self.CompanyName)
def main():
# Create an object
emp01 = Employee("John")
if __name__ == "__main__":
main()
下面提到的代码可以工作,但使用相同的概念,我的代码无法工作,为什么?谁能给我解释一下原因吗?
class Room:
def __init__(self):
self.roomno = 0
self.rcap = 0
self.rooms = {}
self.nog = 10
def addRoom(self):
self.rcap = input("Please enter room capacity:\n")
self.rooms[self.roomno] = self.rcap
class Booking(Room):
def addBooking(self):
while int(self.nog) > int(self.rcap):
print("Guest count exceeds room capacity of: %d" % int(self.rcap))
x = Booking()
x.addRoom()
x.addBooking()
最佳答案
您缺少对父类(super class)的 BasicInfo
方法的调用:
def __init__(self, Name):
print("Employee Name:", Name)
super().BasicInfo()
# ^^Here^^
print("Company Name:", self.CompanyName)
显然,您可以将 super().BasicInfo()
替换为对该类的直接引用:
Company.BasicInfo(self)
<小时/>
在第二个示例中,子类没有定义 __init__
方法,因此它将从父类继承该方法;因此,实例变量将出现在子类中。
关于python - 无法在python中访问基类中的父类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480392/