Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to avoid

phoneData = phone.brand + ";" + phone.name

Any ideas?

Thanks in advance

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading