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
?
您可以在这里定义名称并在声明对象时调用它,例如
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"