Set a variable as in setter

Dave Angel davea at dejaviewphoto.com
Sun May 24 23:54:57 CEST 2009


Kless wrote:
> On 24 mayo, 12:27, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
>   
>> Kless <jonas.... at googlemail.com> wrote:
>>     
>>> 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 =elf._change(bar)  # !!! as setter
>>>       
>> What's wrong with just doing this?:
>>         self.bar =ar
>>     
>
> 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"




More information about the Python-list mailing list