Set a variable as in setter

K

Kless

Is there any way to simplify the next code? Because I'm setting a
variable by default of the same way than it's set in the setter.

-------------------
class Foo(object):
def __init__(self, bar):
self._bar = self._change(bar) # !!! as setter

@property
def bar(self):
return self._bar

@bar.setter
def bar(self, bar):
self._bar = self._change(bar) # !!! as in init

def _change(self, text):
return text + 'any change'
-------------------
 
M

Mike Kazantsev

Is there any way to simplify the next code? Because I'm setting a
variable by default of the same way than it's set in the setter.

Guess it's obvious, but why not use "setattr(self, 'bar', bar)" here, in
__init__ - it'll just call defined setter.
@property
def bar(self):
return self._bar

@bar.setter
def bar(self, bar):
self._bar = self._change(bar) # !!! as in init

def _change(self, text):
return text + 'any change'
-------------------

--
Mike Kazantsev // fraggod.net

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.11 (GNU/Linux)

iEYEARECAAYFAkoZRaIACgkQASbOZpzyXnFELgCgtBsgqLLNf9PfHO/tMtf/AF08
X0oAoNGxKsTo80OHPye8vBnMObwBkliZ
=bVB2
-----END PGP SIGNATURE-----
 
M

Mike Kazantsev

Guess it's obvious, but why not use "setattr(self, 'bar', bar)" here, in
__init__ - it'll just call defined setter.

In fact, "self.bar = bar" is even simplier.
Somehow I thought it wouldn't work here, but it does.


--
Mike Kazantsev // fraggod.net

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.11 (GNU/Linux)

iEYEARECAAYFAkoZSFsACgkQASbOZpzyXnGlzgCggXfnlHnjh/qrx4Z+wVTeEuzR
DC8AnjUPWDk2VaibRheug0T5nyc7xFaB
=zCjh
-----END PGP SIGNATURE-----
 
D

Dave Angel

Kless said:
Because 'bar' is going to be modified before of be saved.
You can't modify bar, it's immutable (string).

Did you try the suggestion, or just assume it won't work? self.bar will
call your setter method just as well from __init__() as it does outside
the class. So that eliminates the need for a separate _change() method.

class Foo(object):
def __init__(self, bar):
self.bar = bar

@property
def bar(self):
return self._bar

@bar.setter
def bar(self, text):
self._bar = text + "any change"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top