Skip to main content
 首页 » 编程设计

python之仅使用静态方法调用继承类的构造函数

2024年10月01日6虾米姐

我有两个 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 数据发送到云服务器。许多其他类继承自此,因此数据传输很容易处理。 Sensor 类用于从各种传感器收集数据。在任何时候都不需要这些类的任何实例,因为数据只是被传递。我使用类的原因是将某些方法组合在一起,同样不是必需的。我唯一需要做的就是运行 Cloud 的构造函数,以便更新类变量。我可以在静态方法中处理这个,但我没有。

同样,只是在寻找反馈。好主意,坏主意......

请您参考如下方法:

既然它实际上是一个静态类变量,难道你不能在 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 实例来初始化变量。此外,每次创建实例时都读取(整个)文件似乎效率低下。