Python 用相同的名称创建现有类的子类 我正在优化现有的代码库,在那里我必须大量使用旧的类和方法,并在适当的地方创建新的模块。

Python 用相同的名称创建现有类的子类 我正在优化现有的代码库,在那里我必须大量使用旧的类和方法,并在适当的地方创建新的模块。,python,Python,现有结构如下所示(还有更多的类,如FooBar,还有一些子模块和file.pys) existing/file.py import foo from bar import baz Variables declaration Some format declaration logger declaration Class FooBar(object): def some_method(self): pass from exisiting.file import *

现有结构如下所示(还有更多的类,如
FooBar
,还有一些子模块和
file.py
s)

existing/file.py

import foo
from bar import baz

Variables declaration
Some format declaration
logger declaration

Class FooBar(object):
    def some_method(self):
        pass
from exisiting.file import *

Class FooBar(FooBar):
    def some_method2(self):
        pass
我目前正在考虑在下面做这件事,虽然它是可行的,但这看起来不是正确的方法

new/file.py

import foo
from bar import baz

Variables declaration
Some format declaration
logger declaration

Class FooBar(object):
    def some_method(self):
        pass
from exisiting.file import *

Class FooBar(FooBar):
    def some_method2(self):
        pass
什么是蟒蛇式的方法

我考虑的另一个选择是可能用其他名称分别导入每个类,但在我看来,
import*
已经涵盖了这一点

PS:这是一个演示如何工作

class Foo():
    def bar(self):
        print "class Foo(), method bar()"

class Foo(Foo):
    def barbar(self):
        print "class Foo(Foo), method barbar()"

variable = Foo()

variable.bar()
"class Foo(), method bar()"

variable.barbar()
"class Foo(Foo), method barbar()"

我不确定您在这里寻找的是什么,但您可以通过以下方式导入每个类:

from existing.file import Foo as oldFoo

然后可以创建一个名为Foo的新类,该类扩展了oldFoo

是否希望用自己的子类覆盖对现有类的所有引用?@DanielRoseman是的。我正在尝试为每个原始类创建新的子类(总共大约25个),以便访问父类的方法,同时为子类定义新方法。另一个要求是保留现有的类命名法。@DanielRoseman进一步解释说,我目前的方法是可行的,但它看起来真的很粗糙,不确定这是否是python的方法。说实话?重新开始。将
existing/file.py
复制到
new/file.py
并编辑它以匹配新代码。在像这样的旧代码之上构建是脆弱的。我认为除了使代码更难理解之外,没有任何其他缺点,尤其是使用
import*