Override Python class variable in subclass based on another class variable

  Kiến thức lập trình

Let’s say I have the following class called A which I cannot change:

class A:
    default = 1
    values = <user_generated_list>

I want to create a subclass of A called B where default is the max value of values. I’ve come up with the following:

class B(A):
    @property
    def default(self):
        return max(self.values)

This seems to work fine:

# user_generated_list = [1, 3, 5]
A().default  # 1
B().default  # 5

Is this an acceptable approach? Is there a better way to do this?

1

LEAVE A COMMENT