Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 682
idlackage Avatar asked Aug 13 '12 00:08

idlackage


1 Answers

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

like image 103
Ryan Haining Avatar answered Oct 11 '22 12:10

Ryan Haining