Python类继承-Base由一个子类修改

Python类继承-Base由一个子类修改,python,class,python-3.x,inheritance,Python,Class,Python 3.x,Inheritance,假设我有一个名为Test的类,它有一个属性items。然后我创建了一个名为Best的子类。它有一个修改类属性项的方法。但是它甚至修改了测试的项目,并且我只为最佳修改项目 class Test(): items = [] class Best(Test): def method(self): type(self).items.append("a test") >>> Best().method() >>> Best.items

假设我有一个名为
Test
的类,它有一个属性items。然后我创建了一个名为
Best
的子类。它有一个修改类属性项的方法。但是它甚至修改了
测试
项目
,并且我只为
最佳
修改
项目

class Test():
    items = []

class Best(Test):
    def method(self):
        type(self).items.append("a test")

>>> Best().method()
>>> Best.items
["a test"]
>>> Test.items 
["a test"]            # This is what I don't want.

您已经将
声明为超类本身的一个属性,因此所有Test实例及其子类都将共享同一个列表。相反,在Test的_; init _;方法中声明它,所以每个实例都有一个列表

在Best中,只需添加到
self.items
,只有Best实例的列表才会更新

class Test(object):
    def __ init __(self)
        self.items = []

class Best(Test):    # Best must inherit from Test
    def method(self):
        self.items.append("a test")

在Python中,您可以通过使用“private”成员获得所需的内容

class Base(object):
    def __init__(self):
        self.__mine = 42  # note the double underscore
    def baseMethod(self):
        return self.__mine

class Derived(Base):
    def __init__(self):
        Base.__init__(self)
        self.__mine = 99

    def derivedMethod(self):
        return self.__mine

obj = Derived()
print(obj.baseMethod(), obj.derivedMethod()) ## ==> 42, 99
这是因为编译时Python将在编译
Base
时用
\u-Base\u-mine
替换名称
\u-mine
,在编译
派生
时用
\u-Derived\u-mine
替换名称


但是请注意,在Python中,虽然根据我的经验,这是可能的,但并不经常使用。在很多情况下,派生类是不需要的,这要归功于“鸭子打字”和委托,这是一些在C++或java语言中不可能的东西。

你的代码不能按你的描述做。 首先,
Best
不是
Test
的子类

class Test():
    items = []

class Best(Test):
    def method(self):
        type(self).items.append("a test")

>>> Best().method()
>>> Best.items
["a test"]
>>> Test.items 
["a test"]            # This is what I don't want.
对于另一个
Best.method()
生成

NameError: name 'self' is not defined
是一个
测试
类属性

t = Test()
t.items.append(1)
更改
测试项目

如定义的
B.items
给出了
AttributeError

 class Best(Test):
    def method(self):
        ...
即使我改变:

class Best():
    def method(self):
        ...
Best.method()
不运行<代码>方法
是一种实例方法。我需要使用
Best().method()
。但是我得到了
属性错误

 class Best(Test):
    def method(self):
        ...
做你所描述的
Best().method()
修改
Test.items
——因为
Test
类属性与子类共享

如其他答案所示,只需为
Best
定义
,即可将其值与
测试
类属性分离

 class Best(Test):
     items = ['other']
     ...

您的
Best
类正在修改
Test
(我假设它是从中继承的),因为
Best
没有自己的
项列表。当您访问
Best.items
时,您正在访问从中继承的列表(即从
Test
class)。如果需要不同的列表,则需要在子类
Best
中显式创建它:

class Best(Test):
    items = [] # hide the inherited list with our own list

    # ...

唯一可行的方法是在子类上创建一个新的
items
——这个新列表还来自哪里?另外,
type(self)
是冗余的。如果在实例上找不到属性,查找机制将查找类上的属性。更好的是,如果不需要实例,那么将该方法声明为类方法

例如


请注意,当从
Best
类调用
method\u test
时,该方法对
Best
类有效。

OK我将尝试。谢谢。这不完全是我想要的,但它仍然帮助我做了一件不同的事情,谢谢。这将是它的实例属性,而不是类的属性。
最好的
应该继承自
测试
?是的,我没有测试我的示例代码,对不起。哦,对不起,我没有测试示例代码。我编辑了这个问题。谢谢