Is it possible for no override for happen? For example:
class A:
def __init__(self, name):
self.name = name
class B(A):
def __init__(self, name):
A.__init__(self, name)
self.name = name + "yes"
Is there any way for self.name
in class B to be independent from that of Class A's, or is it mandatory to use different names?
Prefixing a name with two underscores results in name mangling, which seems to be what you want. for example
class A:
def __init__(self, name):
self.__name = name
def print_name(self):
print self.__name
class B(A):
def __init__(self, name):
A.__init__(self, name)
self.__name = name + "yes"
def print_name(self):
print self.__name
def print_super_name(self):
print self._A__name #class name mangled into attribute
within the class definition, you can address __name
normally (as in the print_name
methods). In subclasses, and anywhere else outside of the class definition, the name of the class is mangled into the attribute name with a preceding underscore.
b = B('so')
b._A__name = 'something'
b._B__name = 'something else'
in the code you posted, the subclass attribute will override the superclass's name
, which is often what you'd want. If you want them to be separate, but with the same variable name, use the underscores
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With