gpt4 book ai didi

python - 一个 Python 谜题

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

如果您对我应该如何在 python 中执行以下任务有任何建议,我正在徘徊:假设我有以下类(class):

class A(object): 
self._classes = []
def magic(self):
c.foo() for c in self._classes

class B(object):
def foo():'''some cool stuff here'''

class C(B):
def foo():'''very cool stuff'''

class D(B):
def foo():'''very cool stuff'''

我想做的是,当类 A 被实例化时,类型 B 的所有类(C 和 D)都将在 self._classes 中被实例化,这意味着 _classes 是 [C(),D()]。

这样做的一般动机是,我希望用户可以轻松添加类,而无需了解使用它们的类。任何帮助都会得到应用。

最佳答案

瞧(感谢 this answerall_subclasses()):

# recursively get all subclasses of a given class
def all_subclasses(cls):
return cls.__subclasses__() + [g for s in cls.__subclasses__()
for g in all_subclasses(s)]

class B(object):
def foo(self): print '''some cool stuff here in B'''

class C(B):
def foo(self): print '''very cool stuff in C'''

class D(B):
def foo(self): print '''very cool stuff in D'''

class E(D):
def foo(self): print '''very cool stuff in E'''

class A(object):
def __init__(self):
self._classes = [cls() for cls in all_subclasses(B)]

def magic(self):
for c in self._classes: c.foo()

# usage:
A().magic()

输出:

very cool stuff in C
very cool stuff in D
very cool stuff in E

关于python - 一个 Python 谜题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26183397/

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