[英]Classes from module with different variables
很难用语言表达我的问题。 基本上我让类处理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_one
和object_two
做同样的事情,但使用不同的变量x
:
模块_a.py
from base import object_one, object_two # with x = 7
模块_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 中有两个以上的类和两个以上的模块a和b我不想为每个类使用在modules_*.py 中设置的类变量。
考虑将 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
。
基础.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()
例如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
的开销很大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.