【问题标题】:How to create an instance by using the name of the class of another instance in python? [duplicate]如何在python中使用另一个实例的类名来创建一个实例? [复制]
【发布时间】:2021-04-02 02:02:55
【问题描述】:

我正在尝试做一些看起来像这样的事情:

class Foo:
    def __init__(self, x, y):
        print(x + y)

a = Foo(10,20)
b = a.CLASSTYPE(20,30)

(注意:我知道没有CLASSTYPE之类的东西)

这样的事情可能吗?如果是,我怎么能在 python 中实现它。 任何事情都将不胜感激,谢谢!

【问题讨论】:

  • 你在问如何获取一个对象的类,不是吗?那只是type(myobj)

标签: python python-3.x class oop


【解决方案1】:

您可以简单地获取a 类型的引用,然后调用它:

b = type(a)(20, 30)

还有a.__class__,但一般应避免直接使用所谓的dunder名称(名称以双下划线开头和结尾)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多