How can I make an alias to a non-function member attribute in a Python class?

后端 未结 6 1700
Happy的楠姐
Happy的楠姐 2021-02-01 05:05

I\'m in the midst of writing a Python library API and I often run into the scenario where my users want multiple different names for the same functions and variables.

If

6条回答
  •  逝去的感伤
    2021-02-01 05:35

    This can be solved in exactly the same way as with class methods. For example:

    class Dummy:
        def __init__(self):
            self._x = 17
    
        @property
        def x(self):
            return self._x
    
        @x.setter
        def x(self, inp):
            self._x = inp
    
        @x.deleter
        def x(self):
            del self._x
    
        # Alias
        xValue = x
    
    d = Dummy()
    print(d.x, d.xValue)
    #=> (17, 17)
    d.x = 0
    print(d.x, d.xValue)
    #=> (0, 0)
    d.xValue = 100
    print(d.x, d.xValue)
    #=> (100, 100)
    

    The two values will always stay in sync. You write the actual property code with the attribute name you prefer, and then you alias it with whatever legacy name(s) you need.

提交回复
热议问题