Chris Cris
Chris Cris

Reputation: 215

decorators and parameters check inside a python class

A class:

class Spam:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

An instantiation:

from Spam import *
c = Spam(1,5,4)

In this case, to perform a check on the input values of 'a' or 'b' or 'c' I've the decorators @property, @a.setter, @b.setter, @c.setter but...what if I need to check this variables but they are not directly copied into 'private' class variables?

I mean

class Egg()
    def __init__(self, a, b, c):
        self.var = (a + b)*c

Say I need to check a < c and c > b, what is the best way to perform checks on variables 'a', 'b', 'c' inside the class Egg and bound their value to some standards if checks are not consistent? Is there any particular decorator? (I need to keep code "clean and easy to uderstand" outside the class...this is why I am not performing checks before instantiation).

Upvotes: 0

Views: 83

Answers (1)

Eric
Eric

Reputation: 97631

Have you considered immutability?

from collections import namedtuple

class Egg(namedtuple('Egg', 'a b c'))
    def __new__(cls, a, b, c):
        assert a < c and c > b
        return super(Egg, cls).__new__(a, b, c)

    @property
    def var(self):
        return (a + b)*c

Upvotes: 1

Related Questions