首页 > 解决方案 > How to create an instance by using the name of the class of another instance in python?

问题描述

I am trying to do something that looks something like this:

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

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

(Note: I know that there is nothing such as CLASSTYPE)

Is something like this possible? And if it is, how could I implement it in python. Anything would be greatly appreciated, thanks!

标签: pythonpython-3.xclassoop

解决方案


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

b = type(a)(20, 30)

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


推荐阅读