+ 7
What is wrong with my code?
https://code.sololearn.com/clxx7nWLeISr/?ref=app Why smartphone class is not inheriting?
4 Antworten
+ 1
You should write:
class Smartphone(Phone):
- 1
# inheritence in python programming
class Phone:
def __init__(self,brand,model_name,price):
self.brand = brand
self.model_name = model_name
self.price = price
def full_name(self):
print (self.brand + self.model_name + str(self.price))
class Smartphone(Phone):
def __init__(self,brand,model_name,price):
super().__init__(brand,model_name,price)
A = Phone("nokia","1100",4500)
B = Smartphone("oneplus","5",3400)
print(A.full_name())
print(B.full_name())
Go this way.
- 1
It seems you want second initialiser, if so you can use classmethod() or make the attributes optional
# 1. classmethod
class Smartphone(Phone):
# note that __init__ is automatically inherited
@classmethod
def WithSpec(cls, brand, model_name, price, ram, internal_memory, rear_camera):
obj = cls(brand, model_name, price)
obj.ram = ram
obj.internal_memory = internal_memory
obj.rear_camera = rear_camera
return obj
C = Smartphone.WithSpec("oneplus", "6", 3400, 4, True, True)
#2. optional attributes
class Smartphone(Phone):
def __init__(self, brand, model_name, price, ram=None, internal_memory=None, rear_camera=None):
super().__init__(brand, model_name, price)
self.ram = ram
self.internal_memory = internal_memory
self.rear_camera = rear_camera
B = Smartphone("oneplus", "5", 3400)
C = Smartphone("oneplus", "6", 3400, 4, True, True)
- 6
In the code Phone is parentclass and Smarphone is childclass
Inheritance mean child aquires properties from parent
since Smartphone child it cannot perfom inheritance in this code
If we want to do so
make Smartphone as parent
Phone as child
Now the code will become
class Smartphone(Phone):
It will work as per request
I am saying same thing what HonFu said
but for me -ve mark he is +ve mark