Python OOP:创建一个是多个类的实例的对象

发布于 2025-01-24 08:45:01 字数 1077 浏览 0 评论 0原文

假设我构建了一些包含一些实例方法的类:

class A:
    def func_of_A(self):
        print("foo")

class B:
    def func_of_B(self):
        print("bar")

如何构造对象/变量c,这是ab的实例代码> ,以便我可以调用c.func_of_a()c.func_of_b()

我当然可以构建一个新的类,该类从Ab和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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱花坊 2025-01-31 08:45:01

您可以使用type(),如@deceze所述

>>> class A:
...     def a():
...         pass
... 
>>> class B:
...     def b():
...         pass
... 
>>> def merge(name: str, *parents):
...     return type(name, parents, dict())
... 
>>> C = merge("C", A, B)
>>> C.a()
>>> C.b()
>>> 

You can use type() for that as @deceze mentioned

>>> class A:
...     def a():
...         pass
... 
>>> class B:
...     def b():
...         pass
... 
>>> def merge(name: str, *parents):
...     return type(name, parents, dict())
... 
>>> C = merge("C", A, B)
>>> C.a()
>>> C.b()
>>> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文