[英]Is there a way to create new variables that work inside a method?
I want to define new variables within a class method, but it just shows AttributeError: 'MyClass' object has no attribute 'var1'
:我想在 class 方法中定义新变量,但它只显示
AttributeError: 'MyClass' object has no attribute 'var1'
:
class MyClass():
def __init__(self, stuff):
self.stuff = stuff
for i in range(len(self.stuff)):
locals()['var' + str(i)] = "e"
d = MyClass("hello")
print(d.var1)
And if I write it this way, it'll say name 'self' is not defined
instead:如果我这样写,它会说
name 'self' is not defined
代替:
class MyClass():
def __init__(self, stuff):
self.stuff = stuff
for i in range(len(self.stuff)):
locals()['var' + str(i)] = "e"
d = MyClass("hello")
print(d.var1)
I know locals()['var' + str(i)] = "e"
will work like this if I just use it outside a method, but I want my class to recieve data from the outside.我知道
locals()['var' + str(i)] = "e"
如果我只是在方法之外使用它,它将像这样工作,但我希望我的 class 从外部接收数据。
class MyClass():
for i in range(len("hello")):
locals()['var' + str(i)] = "e"
d = MyClass()
print(d.var1)
Take a look at setattr() .看看setattr() 。 Looks like you want to set custom attributes on your class instance.
看起来您想在 class 实例上设置自定义属性。 Why you might want to do that is a different topic.
为什么你可能想要这样做是一个不同的话题。
class MyClass:
def __init__(self, stuff):
self.stuff = stuff
for i, letter in enumerate(self.stuff):
setattr(self, f"var{i}", letter)
d = MyClass("hello")
print(d.var0)
# Will print "h".
print(d.var1)
# Will print "e".
print(d.var2)
# Will print "l".
# etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.