I have a class
class Phone:
def __init__(self, brand, name):
self.brand = brand
self.name = name
phone = Phone("apple", "iphone3")
So I want to concatenate both data attributes to result like
"apple; iphone3"
I would like to avoid
phoneData = phone.brand + ";" + phone.name
Any ideas?
Thanks in advance
No way to avoid it. But you can override __str__
and/or __repr__
method of Phone
:
class Phone:
def __init__(self, brand, name):
self.brand = brand
self.name = name
def __str__(self):
return f'{self.brand};{self.name}'
phone = Phone("apple", "iphone3")
print(phone)
output:
apple;iphone3
And a bit of a hack that also can be used (but I wouldn't recommend it, it's more for educational purposes):
phone_data = ';'.join(phone.__dict__.values())
with the same output.