仅使用静态方法

时间:2017-11-13 22:57:22

标签: python inheritance constructor

我有两个Python类。一个继承自另一个。两者都只包含静态方法。继承的类具有需要从外部配置文件初始化的类变量。我试图找到一种方法来获取继承的类的构造函数而不创建实例。

下面的代码是我所做的精益例子。代码有效。但是,我不确定这是不是很糟糕的做法。我没有理由不在使用前实例化该类。我只是想开发一个不需要实例来做我需要它的解决方案,因为类只是静态方法。要求继承类的构造函数被调用。

此外,有人可以告诉我在方法中创建的新类实例发生了什么' foo'?

import json

class Cloud(object):
    val = None  # ....................................... Class Variable

    def __init__(self):  # .............................. Class Constructor
        with open('config.dat', 'r') as f:
            dat = json.load(f)
        Cloud.val = dat['val']  # ....................... overwrite Class Variable
        print('Class Cloud -- constructor called.')

    @staticmethod
    def foo():  # ....................................... static method, does not require instance
        Cloud.__init__(Cloud.__new__(Cloud))  # ......... call the constructor on a NEW instance
        print('Class Cloud, class variable (val):={}'.format(Cloud.val))

class Sensor(Cloud):

    @staticmethod
    def bar():
        print('bar')

# run Static Method of Inherited Class Cloud
# call Class Cloud constructor
Sensor.foo()

编辑:

类Cloud用于将MQTT数据传输到云服务器。许多其他类继承自此,因此可以轻松处理数据传输。传感器类用于从各种传感器收集数据。在任何情况下都不需要这些类的任何实例,因为数据只是传递过来。我使用类的原因是将某些方法组合在一起,同样不是必需的。我唯一需要的是运行Cloud的构造函数,以便更新类变量。我可以在静态方法中处理这个问题,我只是没有。

再次,只是寻找反馈。好主意,坏主意......

1 个答案:

答案 0 :(得分:2)

由于它实际上是一个静态类变量,你不能只在class定义中初始化它吗? 我在谈论这样的事情:

import json

class Cloud(object):
    with open('config.dat', 'r') as f:
        dat = json.load(f)
        val = dat['val']
        del dat  # Keep this variable from becoming a class attribute.

    def __init__(self):  # .............................. Class Constructor
#        with open('config.dat', 'r') as f:
#            dat = json.load(f)
#        Cloud.val = dat['val']  # ....................... overwrite Class Variable
        print('Class Cloud -- constructor called.')

    @staticmethod
    def foo():  # ....................................... static method, does not require instance
#        Cloud.__init__(Cloud.__new__(Cloud))  # ......... call the constructor on a NEW instance
        print('Class Cloud, class variable (val): {}'.format(Cloud.val))

class Sensor(Cloud):

    @staticmethod
    def bar():
        print('bar')

# run Static Method of Inherited Class Cloud
# call Class Cloud constructor
Sensor.foo()

这样您就不需要构造Cloud的丢弃实例来初始化变量。此外,每次创建实例时读取(整个)文件似乎效率低下。

相关问题