-1

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

2
  • 2
    Any reason why you want to avoid phoneData = phone.brand + ";" + phone.name ? Commented Nov 28, 2024 at 11:19
  • In a future, phone class is getting more attributes and I would like to avoid fixing each time. Commented Nov 28, 2024 at 11:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much. Just a question. Does your version upgrade the code? Or is it only a matter of preference?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.