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

后端 未结 6 1795
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:47

    You can provide a __setattr__ and __getattr__ that reference an aliases map:

    class Dummy:
        aliases = {
            'xValue': 'x',
            'another': 'x',
        }
    
        def __init__(self):
            self.x = 17
    
        def __setattr__(self, name, value):
            name = self.aliases.get(name, name)
            object.__setattr__(self, name, value)
    
        def __getattr__(self, name):
            if name == "aliases":
                raise AttributeError  # http://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html
            name = self.aliases.get(name, name)
            return object.__getattribute__(self, name)
    
    
    d = Dummy()
    assert d.x == 17
    assert d.xValue == 17
    d.x = 23
    assert d.xValue == 23
    d.xValue = 1492
    assert d.x == 1492
    

提交回复
热议问题