fqv572
fqv572

Reputation: 39

Python - Concatenate data attributes of a class

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

Upvotes: -1

Views: 41

Answers (1)

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

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.

Upvotes: 1

Related Questions