I'm trying to convert a list to one sequence string, by using a method in OOP. For example, I would like to convert ['Stack', 'over', 'flow', 3] to 'Stackoverflow3'.
When I tried doing that, the results were still returned as a list-
class NewClass:
def __init__(self, array):
self.array = array
def __str__(self):
return "".join(str(i) for i in self.array)
s_1 = ["Stack", "over", "flow", 3]
print(s_1.__str__())
I got this output - ['Stack', 'over', 'flow', 3]
Could you please guide me on how to do it right?
CodePudding user response:
You need to instantiate the class defined:
class NewClass:
def __init__(self, array):
self.array = array
def __str__(self):
return "".join(str(i) for i in self.array)
s_1 = NewClass(["Stack", "over", "flow", 3])
print(s_1) # print 'automatically' uses __str__!
Out:
Stackoverflow3
CodePudding user response:
You need to create an instance of the class 'NewClass' before you pass the list argument. Your code should look like this: `
class NewClass:
def __init__(self, array):
self.array = array
def __str__(self):
return "".join(str(i) for i in self.array)
s_1 = NewClass(["Stack", "over", "flow", 3])
print(s_1.__str__())`