【问题标题】:Make Python module classes able to be called from a separate class使 Python 模块类能够从单独的类中调用
【发布时间】:2017-12-22 11:41:53
【问题描述】:

我目前有一个模块my_module,其中包含classes.py

from . import config
class Class1:
    @staticmethod
    def method_one(x)
        return x + config.constant

    @staticmethod
    def method_two(y)
        return x - config.constant

我的问题是我希望能够拥有多个具有不同 config.constant 值的模块实例。理想情况下,我会有一个名为 MyClass 的新类,其中常量将是一个实例变量,这样就可以工作:

instance1 = MyClass(5)
instance1.Class1.method_one(5) # 10
instance2 = MyClass(0)
instance2.Class1.method_one(5) # 5

有没有办法在不修改 my_module 中的类的情况下做到这一点?

【问题讨论】:

  • 我在这里没有看到类,为什么你要创建一个模块的多个实例而不是一个类的多个实例?
  • 模块有多个类,每个类都使用模块常量。我想创建一个功能与模块完全相同的类。即my_module.some_class.some_method() = my_class.some_class.some_method()如果my_class的常量实例变量等于my_moduleconfig_constant
  • 不过,您向我们展示的内容中没有课程。根据您似乎认为自己已经向我们展示了课程,以及您想如何做instance1.module_class1 之类的事情,我认为您可能误解了课程的实际含义。
  • 编辑了帖子,希望现在更有意义。

标签: python class methods module


【解决方案1】:

使其成为静态方法。

class MyClass(object):

    @staticmethod
    def my_method(num):
        return num + num

然后你可以从另一个文件中使用它(假设文件是​​my_module.py:

import my_module
my_module.MyClass.my_method(2)
>>>4

my_module.py

def __init__(self, constant):
    self.constant = constant

def my_method(self, num):
    return self.constant + num

some_other_file.py

import my_module
MyClass = type('MyClass', (), my_module.__dict__)
my_instance = MyClass(3)
my_instance.my_method(4)
>>> 7

【讨论】:

  • 这不是我想要的;我应该详细说明,但是模块中包含多个类文件,每个类文件都使用config.constant。我只是想有一个功能类似于模块的类,只能用不同的常量值实例化。
  • 好吧,我认为我可能明白了,但这并没有什么意义。常数是常数,因为它不会改变。这就是恒定的意思。如果您希望它拥有自己的版本,那么您可以在__init__ 方法中设置一个属性。喜欢def __init__(self, constant): self.constant = constant
  • 我想我很难解释它。本质上,我想对模块进行“分类”,如here. 所见,但是,在模块的此类版本中,我希望能够为所有类的常量实例化一个具有不同值的新类模块使用。
  • 好的,好的。我想我终于明白了。将__init__ 方法添加到您的“类”文件并执行此操作。 MyClass = type('MyClass', (), my_module.__dict__) 然后用MyClass(3) 对其进行初始化以设置该文件的常量。这对你有用吗?
  • 我更新了我的原始答案,更清楚地解释了我的意思。
猜你喜欢
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 2019-02-19
  • 2014-06-19
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多