Python OOP:创建一个是多个类的实例的对象
假设我构建了一些包含一些实例方法的类:
class A:
def func_of_A(self):
print("foo")
class B:
def func_of_B(self):
print("bar")
如何构造对象/变量c
,这是a
和b
的实例代码> ,以便我可以调用c.func_of_a()
和c.func_of_b()
?
我当然可以构建一个新的类,该类从A
和b
和Make c
一个成员:
class C(A,B):
pass
c = C()
但这不是我正在寻找的成员为了。每当我计划使用已经建造的组合时,我宁愿不会创建一个新课程。
我还可以创建一个函数来动态定义新类并返回一个实例:
def merge(*inherit_from):
class D(*inherit_from):
pass
return D()
c = merge(A,B)
但是这是无法诅咒的,因为现在MERGE(a,b)
,merge(a)和
MERGE(B)
全部返回相同的类型< class'__ -Main __. Merge。< locals> .d'>
。
应该有一种预期的方法来做到这一点,不应该吗?
是否有一个解决方案可以很好地扩展到涉及的类数量?如果我已经有类A1
,类A2
,...,类A100
,我想构造一些c
成为A2类,A23类,A72类,A99类
的实例,但我该怎么办?考虑到〜2^100组合,为每种组合创建一个新课程几乎是不可能的。
Say I built some classes containing some instance methods:
class A:
def func_of_A(self):
print("foo")
class B:
def func_of_B(self):
print("bar")
How can I construct an object/variable c
that is an instance of both A
and B
, so that I can call both c.func_of_A()
and c.func_of_B()
?
I could of course build a new class inheriting from A
and B
and make c
a member of that:
class C(A,B):
pass
c = C()
But that is not what I am looking for. I would rather not create a new class every time I am planning to use a combination of already built ones.
I could also create a function to dynamically define a new class and return an instance of it:
def merge(*inherit_from):
class D(*inherit_from):
pass
return D()
c = merge(A,B)
but this is beyond cursed, because now merge(A,B)
, merge(A)
and merge(B)
all return the same type <class '__main__.merge.<locals>.D'>
.
There should be an intended way to do this, shouldn't?
Is there a solution that scales well with the number of classes involved? If I already have class A1
, class A2
, ..., class A100
and I want to construct some c
to be an instance of class A2, class A23, class A72, class A99
but not the others how would I do that? Creating a new class for every combination is pretty much impossible, given the ~2^100 combinations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
type()
,如@deceze所述You can use
type()
for that as @deceze mentioned