gpt4 book ai didi

python - 来自python基类的重复数据名称

转载 作者:行者123 更新时间:2023-12-04 17:01:10 25 4
gpt4 key购买 nike

class A:
def __init__(self):
self.num = 1

class B(A):
def __init__(self):
super().__init__()
self.num = 2
这里发生了什么,我可以在实例 A 中使用 num 数据吗?
我可以在 C++ 中执行以下操作:
n = B(); n::A.num

最佳答案

你在这里混淆了实例和类。self __init__ 中的引用方法是当前实例对象,语句self.num = ...设置属性 num在那个实例上。对于设置该属性的代码没有区别,因此 A.__init__() 之间没有区别。方法和 B.__init__()方法设置属性。
换句话说:self.num = 2声明,最后运行,获胜。值 1设置在 A.__init__()被覆盖。
有一个异常(exception);当您使用 names that start with a double underscore (但不以双下划线结尾),然后这些名称会自动重写以包含当前类作为前缀。来自 Identifiers (Names) section of the expression reference documentation :

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam.


所以如果你使用:
class A:
def __init__(self):
self.__num = 1

class B(A):
def __init__(self):
super().__init__()
self.__num = 2
然后是一个实例 b = B()将有两个属性, b._A__numb._B__num是分开的和不同的。此功能的目的是为每个类提供一个单独的命名空间,不会(容易)被子类干扰。
后者的演示:
>>> class A:
... def __init__(self):
... self.__num = 1
...
>>> class B(A):
... def __init__(self):
... super().__init__()
... self.__num = 2
...
>>> b = B()
>>> vars(b)
{'_A__num': 1, '_B__num': 2}
>>> b._A__num
1

关于python - 来自python基类的重复数据名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66107559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com