代码之家  ›  专栏  ›  技术社区  ›  Tech Learner

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

  •  1
  • Tech Learner  · 技术社区  · 6 年前

    我使用的是Python3.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 回复  |  直到 6 年前
        1
  •  1
  •   heemayl    6 年前

    你错过了对超类的调用' BasicInfo 方法:

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

    你可以替换 super().BasicInfo() 显然,直接提到这个类:

    Company.BasicInfo(self)
    

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

        2
  •  0
  •   Sunitha    6 年前

    你的基类方法 BasicInfo 从来没人打过电话。如果你在你的孩子班里 __init__ ,它会起作用的

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