gpt4 book ai didi

Python继承和调用父类构造函数

转载 作者:太空狗 更新时间:2023-10-29 17:13:09 25 4
gpt4 key购买 nike

这就是我在 Python 中尝试做的事情:

class BaseClass:
def __init__(self):
print 'The base class constructor ran!'
self.__test = 42

class ChildClass(BaseClass):

def __init__(self):
print 'The child class constructor ran!'
BaseClass.__init__(self)

def doSomething(self):
print 'Test is: ', self.__test


test = ChildClass()
test.doSomething()

结果是:

AttributeError: ChildClass instance has no attribute '_ChildClass__test'

什么给了?为什么这不像我预期的那样工作?

最佳答案

来自 python 文档:

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 in front of the name, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.

所以你的属性不是__test而是_BaseClass__test

但是您不应该依赖它,而是使用 self._test 并且大多数 python 开发人员会知道该属性是类的内部部分,而不是公共(public)接口(interface)。

关于Python继承和调用父类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1139828/

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