又花了三个小时,我想我也许能找到解决办法。forward-references
如果没有更好的方法,我稍后会结束此问题并发布解决方案
我正在对一个程序进行逆向工程(并尝试使用Python实现它)。在
我有这个问题
例如 我在上课car.py组件,代码如下
__all__ = ("ComponentOfCar");
import Car;
#...#imports other needed packages
class ComponentOfCar(object):
def __init__(self, owner:Car.Car):
self.owner = owner;
self.type = "Default";
#....#create other attribute
像这样的另一个班级(汽车.py)公司名称:
^{pr2}$但在这样做之后,我遇到了一个问题:
Traceback (most recent call last):
File "Y:\Car.py", line 2, in <module>
import ComponentOfCar;
File "Y:\ComponentOfCar.py", line 2, in <module>
import Car;
File "Y:\Car.py", line 4, in <module>
class Car(object):
File "Y:\Car.py", line 10, in Car
def InstallComponen(self, component:ComponentOfCar.ComponentOfCar)->bool:
AttributeError: module 'ComponentOfCar' has no attribute 'ComponentOfCar'
原始程序是用编译语言编写的。里面的类继承非常复杂,它有几百个类,这让我头疼。在
我想通过使用类型注释并将每个类分隔成单独的文件,使这个过程更加清晰。但这必须使用递归导入。在
在谷歌上了半天,我还没找到解决办法,所以我来这里寻求帮助。是Python不能像编译语言那样做到这一点,还是我犯了一些错误?我很困惑。我怎样才能修好它呢。在
很抱歉我的英语不好。谢谢你的时间。:)
待详细说明
下面是这样的反编译类声明的结构(它是c#,整个文件大约有十万行):
// Namespace: GameNamespace
public class Car
{
// Fields
protected List`1<ComponentOfCar> m_lstComponents;
public int ObjectID;
// Methods
public void .ctor(Data data);
public void AddComponent(ComponentOfCar c);
}
// Namespace: GameNamespace
public abstract class ComponentOfCar
{
// Fields
protected Car m_owner;
// Properties
public Car Owner { get; }
// Methods
public Car get_Owner();
public void .ctor(Car owner);
}
或者我的问题是如何使用python来清楚地实现这一点。在
是的,在我的想法中,我知道这是错误的,但我不知道如何使它正确。 我不该把他们分开?或者我可以用另一种方式编写它们(以避免递归导入,并且)执行与c中相同的操作?在
请告诉我解决这个问题的方法,非常感谢。在
又花了三个小时,我想我可能会找到解决办法
forward-references,我正在检查这个。如果没有更好的方法来解决这个问题,我会在稍后关闭这个问题并发布解决方案,它可能会修复我的代码。
希望这会有帮助
在组件.py在
在汽车.py在
^{pr2}$结果:
经过一番考验,我终于找到了解决办法。也许这不是最好的方法(修复递归导入),但它符合我最初的想法。 这是在这个link中说的。在
经过一番思考,我想这可能叫做转发参考,广告根据那个doc链接。我将这两个类改写如下:
在car.py组件公司名称:
在汽车.py公司名称:
^{pr2}$现在,我可以正确地运行这段代码,得到的输出如下:
现在我可以严格按照汇编代码编写python代码了。我可以继续我的工作。在
如果有更好的方法来满足我的需要,请纠正我。在
谢谢大家。:)
相关问题 更多 >
编程相关推荐