gpt4 book ai didi

python - 在很多类 : DRY? 上定义相同的方法覆盖

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:58 25 4
gpt4 key购买 nike

假设我有大量由大型库代码库的 import 定义的类,出于可维护性的原因,我不想修改它们。它们都继承自 BaseClass,而 BaseClass 包含一个我想扩充的方法。我认为以下是可行的解决方案

class MyMixin(object):
def method( self, args):
... # 1. a few lines of code copied from BaseClass's def of method
... # 2. some lines of my code that can't go before or after the copied code
... # 3. and the rest of the copied code

class MyAbcClass( MyMixin, AbcClass):
pass
# many similar lines
class MyZzzClass( MyMixin, ZzzClass):
pass

问题。有没有办法获取 ("MyXxxClass", XxxClass) 元组的列表,并编写定义 MyXxxClasses 的代码?是否足以理解它胜过上面的重复?

最佳答案

使用三个参数 type定义类,然后将它们设置为 the module's global dictionary :

todefine = [('MyAbcClass', AbcClass), ...]
for name, base in todefine:
globals()[name] = type(name, (MyMixin, base), {})

如果要定义的名称遵循您提供的固定模式(`"My"+ 基类名称),您可以通过动态构造要定义的名称来更少地重复自己:

todefine = [AbcClass, ...]
for base in todefine:
name = "My" + base.__name__
globals()[name] = type(name, (MyMixin, base), {})

如果您试图包装给定模块中的所有类,您甚至可以通过内省(introspection)模块以编程方式生成 todefine 来避免显式列出类(如果您知道模块有或没有__all__ 您可以只使用适当的方法,而不是尝试一种方法并默认使用另一种方法):

import inspect
try:
# For modules that define __all__, we want all exported classes
# even if they weren't originally defined in the module
todefine = filter(inspect.isclass, (getattr(somemodule, name) for name in somemodule.__all__))
except AttributeError:
# If __all__ not defined, heuristic approach; exclude private names
# defined with leading underscore, and objects that were imported from
# other modules (so if the module does from itertools import chain,
# we don't wrap chain)
todefine = (obj for name, obj in vars(somemodule).items() if not name.startswith('_') and inspect.isclass(obj) and inspect.getmodule(obj) is somemodule)

关于python - 在很多类 : DRY? 上定义相同的方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32631113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com