与超类变量同名的子类变量 [英] 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"
B 类中的 self.name
有没有办法独立于 A 类中的 self.name
,或者必须使用不同的名称?
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
在类定义中,您可以正常寻址__name
(如在print_name
方法中).在子类中,以及类定义之外的任何其他地方,类的名称被修改为带有前导下划线的属性名称.
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'
在您发布的代码中,子类属性将覆盖超类的name
,这通常是您想要的.如果您希望它们分开,但具有相同的变量名称,请使用下划线
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
这篇关于与超类变量同名的子类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!