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
?
I have tried MyClass = MyClass()
but I get this error:
TypeError: __init__() takes exactly 2 arguments (1 given)
What is the correct way?
You need to pass in an iterable as the first argument; 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
; then you'd rebind that name from the original class to the newly-created instance of MyClass
.
Ummm... just submit an iterable as the my_list
argument?
Demo:
>>> example = MyClass([1, 2, 3])
1
2
3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.