[英]Import subclass from a base class in Python
I have a base class that has a method that creates an instance of a subclass that is called the same as the input string. 我有一个基类,它有一个方法,创建一个子类的实例,调用与输入字符串相同。
This worked before by putting the subclasses and the base class in the same file, and doing something like globals()[name]
. 之前通过将子类和基类放在同一个文件中,并执行类似
globals()[name]
。
Now, however, I've split up the subclasses into other files. 但是,现在,我已将子类拆分为其他文件。 They each have an
import base
statement at the top, so I can't just simply import the subclasses in my base class or there'll be a chain of circular importing. 它们每个都在顶部有一个
import base
语句,所以我不能简单地在我的基类中导入子类,或者只有一个循环导入链。
Is there any workaround for this? 这有什么解决方法吗?
In base.py : 在base.py中 :
from basefactory import BaseFactory
class Base:
def __init__(self, arg1, arg2):
...
def resolve(self, element):
className = typing.getClassName(element)
return BaseFactory.getInstance(className, element, self)
In basefactory.py : 在basefactory.py中 :
from file1 import *
from file2 import *
...
class BaseFactory:
@staticmethod
def getInstance(name, arg1, arg2):
subclass = globals()[name]
return subclass(arg1, arg2)
In file1.py : 在file1.py中 :
from base import Base
class subclass1(Base):
def foo(self):
return self.arg1
From what I'm understanding, you have: 根据我的理解,你有:
One solution would be to create a separate function / class for the factory method, and put it in a separate file from the base class. 一种解决方案是为工厂方法创建单独的函数/类,并将其放在与基类不同的文件中。 This file could import all the files for the base class and derived classes without the circular reference.
此文件可以导入基类和派生类的所有文件,而不使用循环引用。
For example: 例如:
# base.py:
class baseClass():
def __init__(self):
self.name = "Base"
# sub1.py:
from base import baseClass
class sub1Class(baseClass):
def __init__(self):
self.name = "sub1"
# sub2.py:
from base import baseClass
class sub2Class(baseClass):
def __init__(self):
self.name = "sub2"
# factory.py:
from sub1 import sub1Class
from sub2 import sub2Class # should not create an error
mapping = {'sub1': sub1Class, 'sub2': sub2Class}
def create(baseType):
return mapping[baseType]
Actually, a better method might be to use type : 实际上,更好的方法可能是使用类型 :
type(name, bases, dict)
returns a new type object. type(name, bases, dict)
返回一个新类型对象。 This is essentially a dynamic form of the class statement. 这实际上是类语句的动态形式。 The name string is the class name and becomes the
__name__
attribute; 名称字符串是类名,并成为
__name__
属性; the bases tuple itemizes the base classes and becomes the __bases__
attribute; 基元元组列出基类并成为
__bases__
属性; and the dict
dictionary is the namespace containing definitions for class body and becomes the __dict__
attribute. dict
字典是包含类体定义的命名空间,并成为__dict__
属性。 For example, the following two statements create identical type objects: 例如,以下两个语句创建相同的类型对象:
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
Why not move resolve into a manager class? 为什么不将决心转移到经理类? Have a look at the domain class in Class factory in Python .
在Python中查看Class工厂中的域类。 I'm not sure if resolve is needed... you can get the class name directly from
self.__class__.__name__
, and use python functions like type()
and isinstance()
to check if they're particular types. 我不确定是否需要解析...你可以直接从
self.__class__.__name__
获取类名,并使用python函数如type()
和isinstance()
来检查它们是否是特定类型。
Also check out: 还可以看看:
Can you use a string to instantiate a class in python? 你可以使用字符串在python中实例化一个类吗?
Does python have an equivalent to Java Class.forName()? python是否具有Java Class.forName()的等价物?
您可以将失败的import
语句移动到创建子类对象的方法。
I don't know if I understand you, why do you take the subclasses out of the class if you need them inside? 我不知道我是否理解你,如果你需要它们,为什么还要把子类带出课堂? Let then inside the class and, wherever you need them, you can
from class import subclass
然后让我们在类中,并且,无论您需要它们,您都可以
from class import subclass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.