python - 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!
解决方案
您可以简单地获取类型的引用a
,然后调用它:
b = type(a)(20, 30)
还有a.__class__
,但您通常应避免直接使用所谓的 dunder 名称(名称以双下划线开头和结尾)。
推荐阅读
- java - 将 Uri 发送到 MediaMetadataRetriever 中的 setDataSource() 时出现 IllegalArgumentException
- python - 我在 Python 中用于井字游戏的 minimax 算法显示最大递归错误
- c# - 如何在 untiy 2d 中构建传感器以进行机器学习?
- android - 类中的类继承
- postgresql - 即使使用了 remote_apply 同步复制,PostgreSQL 旧 master 报告在重新加入新 master 作为副本时时间线存在差异
- php - 列已创建,但未发布任何值
- javascript - 来自 React.forwardRef 的 ref 为 null
- arrays - Range to Array 在 VBA 中不知何故被搞砸了
- java - Java 泛型编译时错误和原始类型
- angular - 在 Angular 中创建动态级联菜单