简体   繁体   English

如何使用 inheritance 和 super 关键字将 arguments 传递给父 class?

[英]How to pass arguments to parent class with inheritance and with super keyword?

My program is shown below:我的程序如下所示:

class BioData:
    def __init__(self, FirstName, LastName):
        self.FirstName = FirstName
        self.LastName = LastName

class BioData_OP(BioData):
    def __init__(self, age, address):
        super().__init__(FirstName,LastName)
        self.age = age
        self.address = address

mydata = BioData_OP(36,"CNGF","Big","Bee")

I am getting an error.我收到一个错误。 I know if I pass two arguments it won't give me an error but in that case how I can get the first name and last name?我知道如果我通过两个 arguments 它不会给我一个错误,但在这种情况下我怎么能得到名字和姓氏?

I do not want to initialize their values in class BioData_OP .我不想在 class BioData_OP中初始化它们的值。 Do I need to create a separate object for BioData?我需要为 BioData 创建一个单独的 object 吗? if yes then what is the benefit of using inheritance or the super keyword.如果是,那么使用 inheritance 或super关键字有什么好处。

The point of inheritance is to indicate that a certain class (ex. Dog ) has an " is a " relationship with a parent class (ex. Animal ). inheritance的要点是表示某个class(ex. Dog )与父class(ex. Animal )有“”的关系。 So, a Dog is an Animal but with certain properties that only dogs have (or appropriate only to dogs).因此, Dog是一种Animal ,但具有只有狗才有的某些属性(或仅适用于狗)。

class Animal:
  def __init__(self, name):
    self.name = name

class Dog(Animal):
  def __init__(self, name, breed):
    super().__init__(name)
    self.breed = breed

a_dog = Dog("woolfie", "labrador")

Here, the __init__ still takes a name , but also takes in extra attributes specific for a dog, such as breed .在这里, __init__仍然采用name ,但也采用特定于狗的额外属性,例如breed For the common attribute name , that's where you can just pass it along to the parent class with super .对于公共属性name ,您可以将其传递给带有super的父 class 。


So, applying that to your code, I'm assuming a BioData_OP object is a type of BioData , but with added age and address attributes.因此,将其应用于您的代码,我假设BioData_OP object是一种BioData ,但添加了ageaddress属性。 The __init__ should probably still accept the same first name and last name, but then just have added parameters for age and address . __init__可能仍应接受相同的名字和姓氏,但只是为ageaddress添加了参数。

class BioData:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

class BioData_OP(BioData):
    def __init__(self, first_name, last_name, age, address):
        super().__init__(first_name, last_name)
        self.age = age
        self.address = address

mydata = BioData_OP("Big","Bee", 36,"CNGF")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM