我不知道如何表达这个问题。我在下面创建了一个最小的工作示例:
import math
class MyClass:
def __init__(one, two):
self.one = one
self.two = two
def to_logarithm():
return MyClass(self.one, math.log(self.two))
class MyChildClass(MyClass):
def __init__(one, two):
super().__init__(one, two)在上面的示例中,我有一个名为MyClass的父类,它有一个名为to_logarithm的方法。这个方法只是重新创建了类的实例,但是带有参数two的日志。
然后,我有一个继承自MyClass的子类,因此它也继承了to_logarithm方法。但是,如果我运行该方法,我当然会得到一个MyClass实例。我想要做的是,每个孩子(将有不同的行为)将基本上创建一个实例作为自己,只是与对数值。也就是说,我希望如果我调用MyChildClass.to_logarithm(),我基本上会得到MyChildClass(self.one, math.log(self.two)),而不必覆盖方法并对其进行硬编码。有什么办法吗?
发布于 2018-08-06 19:05:55
使用self.__class__。它将是当前实例的类对象。
您的原始代码也缺少一些self。
import math
class MyClass:
def __init__(self, one, two):
self.one = one
self.two = two
def to_logarithm(self):
return self.__class__(self.one, math.log(self.two))
class MyChildClass(MyClass):
pass
print(MyClass(1, 5).to_logarithm())
print(MyChildClass(1, 5).to_logarithm())打印输出
<__main__.MyClass object at 0x10b7c15c0>
<__main__.MyChildClass object at 0x10b7b8550>https://stackoverflow.com/questions/51705975
复制相似问题