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

标签 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()

最佳答案

您缺少对父类(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/

相关文章:

python - 组合元组以形成列表

Python正则表达式获取所有内容,直到字符串中的第一个点

python - Discord.py 如何让机器人不响应 PM

python - python daskivot_table和pandasivot_table之间的区别

python - 在 python 3 中解码 base64 字符串(是否使用 lxml)

python - 正则表达式验证版权

python - 如何使用 Selenium 基于文本和类查找元素?

python - 聚类重叠椭圆

python - ImportError importing .pyd - DLL 加载失败。 Cython

python - 从 cStringIO 对象创建 Python array.array 对象