idlackage
idlackage

Reputation: 2863

Subclass variables with the same name of superclass ones

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?

Upvotes: 9

Views: 6496

Answers (1)

Ryan Haining
Ryan Haining

Reputation: 36882

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

Upvotes: 12

Related Questions