【发布时间】:2015-04-16 05:51:16
【问题描述】:
假设我在一个类中有一个方法,其结构如下:
class TestClass(object):
...
def __init__(self, ...)
...
self.var1 = ...
self.var2 = ...
...
...
def xyz(self, other)
if isinstance(other, TestClass):
...
self.var1 = ...
...
else:
...
self.var2 = ...
...
现在假设我想编写另一个继承自 TestClass 的类 NewTestClass(即 class NewTestClass(TestClass): ... )。
xyz 方法的一个问题是它显式检查 other 变量是否是 TestClass 的实例,并且它还引用实例的属性(即 self.var1、self.var2)。
(a) 如何重写方法 xyz 以便在继承时(在 NewTestClass 中),if 语句的行为类似于 if isinstance(other, NewTestClass): ...(而且我不必重写方法 xyz在NewTestClass) 内?
(b) 同样,假设我在TestClass 中有另一个method,它引用TestClass 中的staticmethod,例如:
@staticmethod
def abc(x):
...
val = ...
...
return val
def mnp(self, ...):
...
x1 = ...
self.var1 = TestClass.abc(x1)
...
这里,mnp 方法使用了TestClass 的staticmethod(即本例中的TestClass.abc)。如何重写TestClass.abc,以便当NewTestClass 继承TestClass 时,它会获得一个方法mnp 将self.var = 行视为等同于self.var1 = NewTestClass.abc(x1)(而且我不必重写mnp 内的方法 NewTestClass) ?
【问题讨论】:
标签: python inheritance python-3.x static-methods