Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a property object to an inline object

Tags:

python

Maybe you could define a property and assign it to a object like so:

a = property(lambda self: getattr(self, "_a"), lambda self, x: setattr(self, "_a", x+1))
b = type("B", (object,), {"a": a, "_a": None})

turns out calling b.a = 2 will overwrite the property.

This is what I try to replicate with a incline objects.

class B:
    _a = None

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, x):
        self._a = x

This might give some clues.

class B:
    _a = None
    a = property(
        lambda self: getattr(self, "_a"), 
        lambda self, x: setattr(self, "_a", x+1)
    )

What is the difference between the first snippet and the second two snippets?

Edit: As per blenders suggestion I understood that

a = property(lambda self: getattr(self, "_a"), lambda self, x: setattr(self, "_a", x+1))
B = type("B", (object,), {"a": a, "_a": None})
b = B()
b.a = 2
print(b.a)

>>> 3
like image 201
Simon Avatar asked Nov 23 '25 16:11

Simon


1 Answers

b = type(...) defines a new type, not an instance of a new type. I'd rename it to B = type(...) and use it as you would the other class definitions:

In [25]: a = property(lambda self: getattr(self, "_a"), lambda self, x: setattr(self, "_a", x+1))

In [26]: B = type("B", (object,), {"a": a, "_a": None})

In [27]: b = B()

In [28]: b.a = 10

In [29]: b.a
Out[29]: 11
like image 151
Blender Avatar answered Nov 26 '25 05:11

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!