Johnny John Boy
Johnny John Boy

Reputation: 3202

How to update an instance variable when another variable is changed?

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.

Upvotes: 2

Views: 521

Answers (1)

khelwood
khelwood

Reputation: 59114

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.

Upvotes: 4

Related Questions