how to create nicer variable interface in python class -
i want variable more set when set it. , interface clean possible.
short: i'd want:
# have class variable can access: print myinstance.var 42 # change variable myinstance.var = 23 # have change kick off method: self.var changed: 23!! hmm.. can do: use variable , setter method:
class test: def __init__(self): self.var = 1 print( 'self.var is: ' + str(self.var) ) def setvar(self, value): self.var = value print( 'self.var changed: ' + str(self.var) ) t = test() self.var is: 1 # have t.var @ hand: print t.var 1 # , change way t.setvar(5) self.var changed: 5 but have 2 different things work with.. ok make method interact var:
class test: def __init__(self): self.var = 1 print( 'self.var is: ' + str(self.var) ) def method(self, value=none): if value == none: return self.var self.var = value print( 'self.var changed: ' + str(self.var) ) t = test() self.var is: 1 # value then: print t.method() 1 # set it: t.method(4) self.var changed: 4 # , verifiy: print t.method() 4 this nice already. i've seen in different post on other languages. dunno. there better solution in python?!?
maybe i'm paranoid but me it'd feel nicer t.var = 5 , have kicked off too.
i think want python properties. check this out. like:
class test: def __init__(self): self._var = 1 @property def var(self): return self._var @var.setter def var(self, value): # add stuff here want happen on var assignment self._var = value
Comments
Post a Comment