Search code examples
pythonpython-3.xclasspropertiespython-descriptors

Is there a pre-defined python descriptor class?


I want to create a class that has a whole lot of properties that for the most part will be just get and set. Here is an example MyClass()

>>> class MyClass():
...     def getx(self): return self.__x
...     def setx(self, value): self.__x = value
...     def delx(self): del self.__x
...     x = property(getx, setx, delx, "I'm the 'x' property.")
...     y = property(getx, setx, delx, "I'm the 'y' property.")
...
>>> bar = MyClass()
>>> bar.x = 'jeff'
>>> bar.y = 3
>>> print(bar.x)
3
>>> print(bar.y)
3
>>>

Here the x and y properties are the same, so if I want x and y to be unique I will need a new getx/setx/delx for each one.

This example works better.

>>> class MyClassBase():
...     def __init__(self, initval=None):
...         self.val = initval
...     def __get__(self, obj, objtype):
...         return self.val
...     def __set__(self, obj, val):
...         self.val = val
...
>>> class MyClassFinal():
...     x = MyClassBase(1)
...     y = MyClassBase('xyzzy')
...
>>> foo = MyClassFinal()
>>> foo.x = 2
>>> print(foo.x)
2
>>> print(foo.y)
xyzzy
>>>

I think MyClassBase() is what they call (or is the equivalent of) a descriptor class. Now the properties x, y (and any others I choose to add to MyClassFinal() ) are independent.

It seems odd I need to create MyClassBase() on my own. Isn't this (or something equivalent) already defined somewhere so I don't need to create my own?

I am also open to a different example of how to create a class with a lot of properties and a minimum of code.


Solution

  • Ahhh! I'm making things way too complicated. Apparently all I need to do is this:

    >>> class MyClassSimple:
    ...     x = 1
    ...     y = 'blue'
    ...     def __str__(self):
    ...         return f'{self.x}, {self.y}'
    ...
    >>> zot = MyClassSimple()
    >>> print(zot)
    1, blue
    >>> zot.x = 'red'
    >>> zot.y = 3
    >>> print(zot)
    red, 3