gpt4 book ai didi

Python OOO 设计多类

转载 作者:行者123 更新时间:2023-11-28 22:01:40 25 4
gpt4 key购买 nike

我有一个父类和一个子类,并试图实例化子类以继承父类的属性。

这段代码工作得很好,但想知道是否有办法让 self.list1 保持私有(private),即;如果我声明 self.__list1 则子类无法访问它。

我能否覆盖子类方法以将 self.__list1 保持为私有(private)?

class parent(object):
def __init__(self,x,y):
self.x = x
self.y = y
self.list1 = ['a','b','c']
print('self.x',self.x)
print('self.y',self.y)

class child(parent):
def test(self):
print('In child self.x',self.x)
print('In child self.list1',self.list1)

class test(object):
def __init__(self,x1,y1):
self.x1 = x1
self.y1 = y1

def process(self):
childobj = child(self.x1,self.y1)
childobj.test()

pass


def main():
testx = test(2,3)
testx.process()

最佳答案

来自docs :

Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

带有两个下划线的前缀调用 name mangling , 是否尊重这些变量/方法的“隐私性”取决于您的客户

关于Python OOO 设计多类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12712515/

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