[英]What is the correct way to run this class?
I have this class: 我有这个课:
class MyClass:
def __init__(self, my_list):
for item in my_list:
print(item)
How can I set a variable to run MyClass()
since it requires my_list
? 由于需要
my_list
如何设置变量以运行MyClass()
?
I have tried MyClass = MyClass()
but I get this error: 我已经尝试过
MyClass = MyClass()
但出现此错误:
TypeError: __init__() takes exactly 2 arguments (1 given)
What is the correct way? 正确的方法是什么?
You need to pass in an iterable as the first argument; 您需要将iterable作为第一个参数传递; a list for example:
列表,例如:
instance = MyClass(['a', 'b', 'c'])
but anything that can be looped over will do; 但是任何可以循环的都可以; so a tuple, a string, a dictionary, a file object will all do.
因此,元组,字符串,字典,文件对象都可以。
Don't assign the result back to MyClass
; 不要将结果分配回
MyClass
; then you'd rebind that name from the original class to the newly-created instance of MyClass
. 然后将名称从原始类重新绑定到新创建的
MyClass
实例。
Ummm... just submit an iterable as the my_list
argument? 嗯...只是提交一个可迭代的
my_list
参数?
Demo: 演示:
>>> example = MyClass([1, 2, 3])
1
2
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.