Setting attribute with property decorator

4289 views python
-1

I've defined a class which returns an instance with a set of default values, where one of these would be overwritten depending on the received parameter p:

class params:
    def __init__(self, p):
        self.n = 100_000
        self.k = 20
        self.d = 50
        getattr(self, p) 
    @property
    def range_k(self):
        p.k = np.arange(21,10_000,100)) 
    @property
    def range_n(self):
        p.n = np.arange(21,1_000_000,50_000)
    @property
    def range_d(self):
        p.d = np.arange(2,2000,100)

So if i create an instance of the class as:

p=params('range_k')

I would want p.k to be a sequence set by range_k instead of its default value set in the init method.

In order to achieve this I have added @property decorators along with these methods to set different atributes according to p, otherwise the attributes can not be modified. My question is, is this the correct way of doing so? Or are there other more appropiate ways?

answered question

I have no idea what you are trying to acheive, but your setattr call is uneccessarily confusing. Just do self.k = np.arange(...) or whatever.

Well yes @FHTMitchell its just an alternative way of doing so

No, it's not just an alternate way. One is the standard and the other is a fallback for when you need dynamic attributes. Don't use getattr/setattr unless you absolutely must.

1 Answer

12

Your way of doing it is overly and unneccessarily confusing. Just handle it in the __init__ method

class params:
    def __init__(self, p):
        self.n = 100_000
        self.k = 20
        self.d = 50
        if p == 'range_k':
             self.k = np.arange(21,10_000,100)
        elif p == 'range_n':
             self.n = np.arange(21,1_000_000,50_000)
        elif p == 'range_d':
             self.d = np.arange(2,2000,100)
        else:
             raise ValueError(f'{p} invalid')

posted this

Have an answer?

JD

Please login first before posting an answer.