创建新类子类化具有相同名称的现有类

2024-04-20 09:48:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在优化现有的代码库,在那里我必须大量使用旧的类和方法,并在适当的地方创建新的模块。你知道吗

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

existing/file.py

import foo
from bar import baz

Variables declaration
Some format declaration
logger declaration

Class FooBar(object):
    def some_method(self):
        pass

我目前正在考虑在下面做这件事,这看起来不是正确的方式做它,虽然它的工作。你知道吗

new/file.py

from exisiting.file import *

Class FooBar(FooBar):
    def some_method2(self):
        pass

什么是Python式的方法?你知道吗

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

附言:这是一个演示如何工作

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()"

Tags: 模块方法pyimportselffoodefbar
1条回答
网友
1楼 · 发布于 2024-04-20 09:48:08

我不太清楚您在这里要找什么,但您可以通过以下方式导入每个类:

from existing.file import Foo as oldFoo

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

相关问题 更多 >