【发布时间】:2017-08-08 16:04:14
【问题描述】:
我是 Python 新手,并试图了解执行以下操作的最正确方法是什么:
我有一个名为“Sample”的基类。它具有一些属性,例如dp,tp等。
我还有几个从这个基础派生的子类,如 SampleA、SampleB 等。它们有几个不同的属性。使用这些独特的属性计算属性之一。而且这个计算非常重复,所以我想写一个方法,在每个类中调用它来计算参数的值。
class Sample(object):
tp = 4
dp = 4.2
por = 0.007
def common_method(self, arg1, arg2)
return self.tp - arg1 * arg2
class SampleA(Sample)
arg1 = 0.1
arg2 = 2
# I want to calculate arg3, but I don't know how to call the
# common_method here.
class SampleB(Sample)
.
.
.
我在提问之前查了一下,但没有看到类似的问题。
非常感谢您。
【问题讨论】:
-
common_method()需要一个对象,但您仍在类声明中。common_method()还有其他用途吗?因为那样你就可以把它设为class method 并通过Sample.common_method()引用它。 -
Python 2 还是 Python 3?
-
@dhke 我考虑只在课堂上使用 common_method。
-
@Jared 适用于 Python 3
-
arg3 = Sample().common_method(arg1, arg2)
标签: python inheritance parameter-passing superclass