【问题标题】:Calculating a class parameter using a super method使用超级方法计算类参数
【发布时间】: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


【解决方案1】:

这可能是元类有意义的少数情况之一。

class CommonProperty(type):
    @property
    def common_property(cls):
        return cls.tp - cls.arg1 * cls.arg2

class Sample(object, metaclass=CommonProperty):
    tp = 4

class SampleA(Sample):
    arg1 = 0.2
    arg2 = 2

print(SampleA.common_property) # 3.6

想法是将property 分配给由子类继承和完成的元类。元类在这里很自然,因为目标是创建一个类property,而不是一个实例property,并且一个类是元类的一个实例。

【讨论】:

    【解决方案2】:

    解决方法是dhke在原问题的cmets中提出的:

    common_method() 需要一个对象,但您仍在类声明中。 common_method() 还有其他用途吗?因为那样你就可以把它设为class method 并通过Sample.common_method() 引用它

    我认为将它应用到代码中会更好:

    class Sample(object):
        tp = 4
        dp = 4.2
        por = 0.007
    
    @classmethod
    def common_method(self, arg1, arg2)
        return self.tp - arg1 * arg2
    
    class SampleA(Sample)
        arg1 = 0.1
        arg2 = 2
        arg3 = Sample.common_method(arg1, arg2)  # 3.8
    
    class SampleB(Sample):
    
    .
    .
    .
    

    非常感谢您帮我解决这个问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多