Stack Overflow Asked by mather on November 18, 2021
I have a Multiple Parent class and the superparent class is the
class Item:
def __init__(self, name):
self.name = name
def print_name(self):
print("The item name is " + self.name)
and the base class is:
class Gadget(Item):
def __init__(self, name,
version):
self.name = name
self.version = version
def print_attribute(self):
pass
#do for attribute
The child of the base class is:
class Mobile_Phone(Gadget):
def __init__():
pass
so when i instatiate the child class
item = Mobile_Phone("Iphone", "iOS")
item.print_name()
it gives me an error the contuctor has 0 positional argument but 3 were given
If your child class initializer doesn't do anything with the arguments you're passing, then they're lost. In the model you've outlined, you could simply omit the initializer in the child class to get what you want.
class MobilePhone(Gadget): # PEP8 calls for CamelCase here
pass
In this case, the initializer inherited from Gadget
is setting self.name
which the inherited Item.print_name
references.
Answered by Sam Morgan on November 18, 2021
You need to understand the concept of OOPs and if you send arguments during object construction then your constructor should have parameters to hold the arguments.
item.py
class Item:
def __init__(self, name):
self.name = name
def print_name(self):
print("The item name is " + self.name)
Gadget.py
from item import Item
class Gadget(Item):
def __init__(self, name, version):
Item.__init__(self, name)
self.version = version
def print_attribute(self):
print(self.name)
print(self.version)
Mobile_Phone.py
from Gadget import Gadget
class Mobile_Phone(Gadget):
def __init__(self, name, version):
Gadget.__init__(self, name, version)
item = Mobile_Phone("Iphone", "iOS")
item.print_name()
Output:
The item name is Iphone
Answered by bigbounty on November 18, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP