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

后端 未结 6 1684
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:53

    This function takes a attribute name and return a property that work as an alias to get and set.

    def alias_attribute(field_name: str) -> property:
        """
        This function takes the attribute name of field to make a alias and return
        a property that work to get and set.
        """
        field = property(lambda self: getattr(self, field_name))
        field = field.setter(lambda self, value: setattr(self, field_name, value))
        return field
    

    Example:

    >>> class A:
    ...     name_alias = alias_attribute('name')
    ...     def __init__(self, name):
    ...         self.name = name
    ... a = A('Pepe')
    
    >>> a.name
    'Pepe'
    
    >>> a.name_alias
    'Pepe'
    
    >>> a.name_alias = 'Juan'
    
    >>> a.name
    'Juan'
    

提交回复
热议问题