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