Python中如何根据对象的创建方法动态初始化变量?

问题描述 投票:0回答:1
class obj(object):
    def __init__(self):
        self.name = ...  # How to set this variable dynaically by using the variable name (on create) or the object name?


var = obj()
print(var.name)  # prints "var" (assigned variable name)

print(obj().name)  # prints "obj"

目前,它们都打印“obj”。

如何根据

self.name
对象的创建方式来设置
obj

python-3.x oop variables
1个回答
0
投票

您可以在这里定义名称并在声明对象时调用它,例如

class obj(object):
    def __init__(self, name):
        self.name = name

var = obj("Hello World")

print(obj.name) # output "Hello World"

somestr = "random string"

var2 = obj(somestr)

print(var2) # output "random string"
© www.soinside.com 2019 - 2024. All rights reserved.