Subclass variables with the same name of superclass ones

谁说胖子不能爱 提交于 2021-01-27 04:43:50

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/11927055/subclass-variables-with-the-same-name-of-superclass-ones

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!