Reputation: 72
i have a question. In oops using python, super can access the method or constructor , but not the attributes . Why is that??
class Phone:
def __init__(self, price, brand, camera):
print ("Inside phone constructor")
self.__price = price
self.brand = brand
self.camera = camera
def buy(self):
print ("Buying a phone")
def return_phone(self):
print ("Returning a phone")
class FeaturePhone(Phone):
pass
class SmartPhone(Phone):
def __init__(self, price, brand, camera, os, ram):
super().__init__(price, brand, camera)
self.os = os
self.ram = ram
print ("Inside smartphone constructor")
def buy(self):
print(super().camera) #Error
print ("Buying a smartphone")
s=SmartPhone(20000, "Samsung", 12, "Android", 2)
print(s.buy()) #error
print(s.brand)
Can anyone please explain?? If possible then how?
Upvotes: 5
Views: 2002
Reputation: 7977
You don't have to access the parent class to use one of its methods. Your class-SmartPhone
inherits from the Phone
class which allows you to access its attributes and methods using self
. So you only need to call self.buy()
to be able to use the method
class Phone:
def __init__(self, price, brand, camera):
print ("Inside phone constructor")
self.__price = price
self.brand = brand
self.camera = camera
def buy(self):
print ("Buying a phone")
def return_phone(self):
print ("Returning a phone")
class FeaturePhone(Phone):
pass
class SmartPhone(Phone):
def __init__(self, price, brand, camera, os, ram):
super().__init__(price, brand, camera)
self.os = os
self.ram = ram
print ("Inside smartphone constructor")
def buy(self):
print(self.camera)
print ("Buying a smartphone")
s=SmartPhone(20000, "Samsung", 12, "Android", 2)
print(s.buy()) # this works
print(s.brand)
Upvotes: 0
Reputation: 443
First I thought - it's obvious. And, then, it is actually an interesting question, and I learned something new today.
super() doesn't return the instantiated class object. It returns an instance of "super" class that takes the class "SmartPhone" and "SmartPhone object" as arguments. It then runs this closure.
As such, you cannot get to the attributes of super class on the value of super() because it's an instance of "super" class.
https://docs.python.org/3.7/library/functions.html#super
Upvotes: 3