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?
I do not want to initialize their values in class BioData_OP
. Do I need to create a separate object for BioData? if yes then what is the benefit of using inheritance or the super
keyword.
The point of inheritance is to indicate that a certain class (ex. Dog
) has an " is a " relationship with a parent class (ex. Animal
). So, a Dog
is an Animal
but with certain properties that only dogs have (or appropriate only to dogs).
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
. For the common attribute name
, that's where you can just pass it along to the parent class with super
.
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. The __init__
should probably still accept the same first name and last name, but then just have added parameters for age
and address
.
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.