无法访问python基类中的父类成员

时间:2018-07-23 13:48:18

标签: python python-3.x python-2.7 class oop

我正在使用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()

2 个答案:

答案 0 :(得分:1)

您缺少对超类的BasicInfo方法的调用:

 def __init__(self, Name):
     print("Employee Name:", Name)
     super().BasicInfo()
     # ^^Here^^
     print("Company Name:", self.CompanyName)

您显然可以直接引用该类来代替super().BasicInfo()

Company.BasicInfo(self)

在第二个示例中,子类未定义__init__方法,因此它将从父类继承该方法。结果,实例变量将出现在子类中。

答案 1 :(得分:0)

您的基类方法BasicInfo永远不会被调用。如果您在子类的__init__中显式调用它,那么它将起作用

class Employee(Company):
    # constructor
    def __init__(self, Name):
        super(Employee, self).BasicInfo()
        print("Employee Name:", Name)
        print("Company Name:", self.CompanyName)