【问题标题】:Classes from module with different variables来自具有不同变量的模块的类
【发布时间】:2015-10-09 11:57:12
【问题描述】:

很难用语言表达我的问题。基本上我已经让类处理 base.py 中的所有内容:

x = 3
class object_one(object):
    def __init__(self):
        self.x = x+3
class object_two(object):
    def __init__(self):
        self.x = x**2
        self.y = object_one()

这些是我的基本对象。现在我需要object_oneobject_two 多次做同样的事情,但使用不同的变量x

module_a.py

from base import object_one, object_two    # with x = 7

module_b.py

from base import object_one, object_two    # with x = 13

但是 module_*.py 怎么必须看起来像我得到的那样

import module_a, module_b
print(module_a.object_one().x, module_a.object_two().y.x)   # Output:  49  49
print(module_b.object_one().x, module_b.object_two().y.x)   # Output: 169 169

因为base.py中有两个以上的类和两个以上的模块ab我不想用modules_*.py 中为每个类设置的类变量。

【问题讨论】:

  • 你为什么要这样做?你到底想达到什么目的?这听起来好像是创建非常难以维护的代码的好方法。
  • module_*.py 是不同的设备(锁定放大器、舞台控制器等)。在 base.py 中,每个设备的不同 模型 都有多个容器(首选项、API、GUI...)(例如 Lock-In:Stanford Research、Signal恢复等)在x 中给出。
  • 为什么 base.py 的顶部有 x=3 ,在需要的时候将 x 作为参数传递给对象构造不是更好吗?
  • 您是否打算编写根据 x 的值执行不同操作的代码?面向对象的方法将是派生/专用类,每个类都实现特定 x 值的行为。然后,您实例化这些专用类的产品代码也会获得正确的行为。
  • 不,因为这需要两件事: 1. 我必须将相同的x 分别传递给 base.py 的每个类。 (这就是我尽量避免使用类变量的原因) 2. 在 module_*.py 中,我需要类而不是它的实例。

标签: python class import module


【解决方案1】:

考虑将 x 和 ObjectOne 作为参数传递:

class ObjectOne:
    def __init__(self, x):
    self.x = x

class ObjectTwo:
    def __init__(self, obj):
        self.x = obj.x**2
        self.y = obj

那么module_a.py(和module_b.py)应该包含:

x = 7 # in module_b.py x = 13

然后,你的主程序:

import base, module_a, module_b

a1 = base.ObjectOne(module_a.x)
a2 = base.ObjectTwo(a1)

b1 = base.ObjectOne(module_b.x)
b2 = base.ObjectTwo(b1)

print(a1.x, a2.y.x)
print(b1.x, b2.y.x)

你没有指定版本,我从 print() 假设它是 Python3,但在 Python3 中你不需要类定义中的对象。

【讨论】:

  • 不幸的是,您传播x 的方法不适用于我的具体问题。实际上,x 中只有一部分存储在object_one 中,而object_two 中需要另一部分。
【解决方案2】:

我现在用类变量做到了。不幸的是,这需要定义新的子类并重复 x

base.py

class object_one(object):
    x = 3
    def __init__(self):
        self.x = type(self).x + 3
class object_two(object):
    x = 3
    class_object_one = object_one
    def __init__(self):
        self.x = type(self).x**2
        self.y = type(self).class_object_one()

e。 G。 module_a.py

import base

class object_one(base.object_one):
    x = 7
class object_two(base.object_two):
    x = 7
    class_object_one = object_one

每个 module_*.py 仅用于更改 x 就会产生很多开销。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2014-01-27
    • 1970-01-01
    • 2016-11-22
    相关资源
    最近更新 更多