【问题标题】:How can I correctly implement this example of using classes?我怎样才能正确地实现这个使用类的例子?
【发布时间】:2017-03-23 13:15:46
【问题描述】:

在以下示例中,可以根据未来情况的上下文选择常量。

class Constants:
    SPEEDLIGHT = 3 * 10**8
    GRAVITY = 9.81

C = Constants()
print(C.GRAVITY)
>> 9.81

这并不太难,因为每个数量都是固定常数。但是假设我想为函数做类似的事情。在下面的第一段代码中,我指定了可积变量x 和固定参数ab 的两个分布。

class IntegrableDistribution:
    def Gaussian(x,a,b):
        cnorm = 1 / ( b * (2 * pi)**(1/2) )
        return cnorm * np.exp( (-1) * (x-a)**2 / (2 * b**2) )
    # Gaussian = Gaussian(x,a,b)

    def Lognormal(x,a,b):
        cnorm = 1 / ( b * (2 * pi)**(1/2) )
        return cnorm * exp( (-1) * (np.log(x)-a)**2 / (2 * b**2) ) / x
    # Lognormal = Lognormal(x,a,b)

我试图命名这些分布,以便它们可以被调用。这导致了一条错误消息,因此上面注释掉了代码。在下一段代码中,我尝试使用输入来选择要集成的分布(尽管我觉得它效率极低)。

Integrable = IntegrableDistribution()

class CallIntegrableDistribution:

    def Model():

        def Pick():
            """
            1 :   Gaussian Distribution
            2 :   Lognormal Distribution
            """
            self.cmnd = cmnd
            cmnd = int(input("Pick a Distribution Model:    "))
            return cmnd

        self.cmnd = cmnd

        if cmnd == 1:
            Distribution = Integrable.Gaussian
        if cmnd == 2:
            Distribution = Integrable.Lognormal

        return Distribution

OR ALTERNATIVELY

    cmnd = {
        1: Gaussian,
        2: Lognormal,
    }

我并不真正关心分布问题;我只是用它来展示我的已知和未知。有哪些方法可以正确地做到这一点或使用类或字典进行类似/更简单的操作?

【问题讨论】:

  • 1.错误是什么? 2. 不要给函数大写名称。这是为课程保留的。
  • TypeError: unsupported operand type(s) for *: 'property' and 'float'

标签: python-3.x class dictionary chaining keyword-argument


【解决方案1】:

使用static methods:

class IntegrableDistribution:
    @staticmethod
    def Gaussian(x,a,b):
        cnorm = 1 / ( b * (2 * pi)**(1/2) )
        return cnorm * np.exp( (-1) * (x-a)**2 / (2 * b**2) )

    @staticmethod
    def Lognormal(x,a,b):
        cnorm = 1 / ( b * (2 * pi)**(1/2) )
        return cnorm * exp( (-1) * (np.log(x)-a)**2 / (2 * b**2) ) / x

及用法:

some_result = IntegrableDistribution.Gaussian(1, 2, 3)
another_result = IntegrableDistribution.Lognormal(1, 2, 3)

【讨论】:

  • 这更有意义,给了我一些可以玩的东西,谢谢。根据链接的文档,“静态方法不接收隐式的第一个参数。”这是否意味着我不能将 x 作为函数变量而不是固定参数传递?
  • @mikey。不。这意味着与实例方法不同,当调用静态方法时,第一个参数不是调用该方法的实例(这是有道理的,因为 没有 实例)。看到这个答案:stackoverflow.com/a/1669524/1453822
猜你喜欢
  • 2019-11-10
  • 2016-06-15
  • 2021-09-24
  • 2013-09-28
  • 2021-10-01
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多