0

I need a approach to this, it's quite simple, but something don't seem right. I have my MyClass which has foo and bar, that not always are instantiated, and I have this property baz, that will compose of foo and bar.

class MyClass(object)
    def __init__(self, *args, **kwargs):
        self.foo = kwargs('foo', None)
        self.bar = kwargs('bar', None)

    @property
    def baz(self):
        if self.foo is not None and self.bar is not None
            return self.foo + self.bar
        else:
            return None

    @baz.setter
    def baz(self, baz):
        self.__baz = baz

# i plan using outside also
my_class = MyClass(foo=1,bar=2)
print my_class.baz
# 3
my_class = MyClass(foo=1)
print my_class.baz
# None

It's right having a @property that will only have this composed return value?

Should i use another approach? like __setattr__?

Edit: The duplicate doesnt answer my question, the class im using has a object inheritance, my question is about if it's the @property getter can return baz value as foo + bar instead of another approach

Patricio
  • 403
  • 3
  • 10
  • 1
    `def MyClass()` makes `MyClass` a function – ForceBru Apr 23 '16 at 18:37
  • 2
    You are using Python 2, so you have an old-style class here. Properties only work properly on *new-style* classes. Inherit from `object`. – Martijn Pieters Apr 23 '16 at 18:38
  • Oh right!, it was a typo but edited, thanks – Patricio Apr 23 '16 at 18:42
  • 1
    Note that you are setting the attribute `self.__baz`, but never check for that in the getter; not sure what you wanted to achieve there. As for a property producing a value from other attributes, that's entirely a valid use-case. – Martijn Pieters Apr 23 '16 at 18:53
  • I just want a `baz` attribute produced by other attributes, and doesn't know if with `@property` was a correct approach because of the `@baz.setter`, but i didn't check and its possible don't define the setter. – Patricio Apr 23 '16 at 19:08

0 Answers0