Here's a snippet of the code where the parent class is Apparel. Apparel has an attribute __price. I next define a class Cotton that inherits from class Apparel. I use super() to invoke the parent methods.
class Apparel: def __init__(self,price,item_type): self.__price = price self.__item_type = item_type def calculate_price(self): self.__price = self.__price + 0.05*self.__price Snippet of class Cotton:
class Cotton(Apparel): def __init__(self,price,discount): self.__discount = discount super().__init__(price,"Cotton") def calculate_price(self): super().calculate_price() self.__price = self.__price - self.__discount def get_price(self): return self.__price Having invoked the parent method using super(), I expect that the attribute __price from the parent will be available to the child in that particular method. However, I get an error on running this:
c1 = Cotton(25000,2500) c1.calculate_price() print (c1.get_price()) And, the error is as follows: AttributeError: 'Cotton' object has no attribute '_Cotton__price'
If it is due to name mangling, how to keep the attributes "super private" at the same time access the attributes in the child classes. I tried several variations like trying to access __price by using Apparel.__price instead of self.__price in class Cotton, still does not work. Trying to check if am being silly somewhere, still can't figure out.
__are name mangled in python to add the class name in front of them (en.wikipedia.org/wiki/Name_mangling#Python), use either single or no underscore to avoid this issue__priceinto_Apparel__pricein theApparelclass, and into_Cotton__pricein theCottonclass. While you could access those mangled names directly, so can whatever code you expect your private names to exclude from tinkering with your internals. Better to use a single underscore, which won't be mangled, but says to your users "This is intended to be private, and it is not part of the supported API".