2

I have the following class and I want the instance variable api_id_bytes to update.

class ExampleClass:
    def __init__(self):
        self.api_key = ""
        self.api_id = ""
        self.api_id_bytes = self.api_key.encode('utf-8')

I'd like to be able to have this outcome:

>>>conn = ExampleClass()
>>>conn.api_key = "123"
>>>conn.api_id = "abc"

>>>print(conn.api_id_bytes)
b'123'
>>>

I basically need the self.api_key.encode('utf-8') to run when an api_id is entered but it doesn't, it only does through the initial conn = ExampleClass().

I'm not sure what this is called so searching didn't find an answer.

3

1 Answer 1

4

Here's how you could do it by making api_id_bytes a property.

class ExampleClass:
    def __init__(self):
        self.api_key = ""
        self.api_id = ""
    @property
    def api_id_bytes(self):
        return self.api_key.encode('utf-8')

Now conn.api_id_bytes will always be correct for the current value of conn.api_key.

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

1 Comment

Legend, thank you for taking the time to post that. I read the docs others had suggest but this worked perfectly!

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.