问题描述
我正在编写一个Python库API,我经常遇到用户需要为同一个函数和变量使用多个不同名称的情况。
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.
如果我有一个Python类的函数 foo()
,我想要一个别名为 bar()
,这很容易:
If I have a Python class with the function foo()
and I want to make an alias to it called bar()
, that's super easy:
class Dummy(object):
def __init__(self):
pass
def foo(self):
pass
bar = foo
现在我可以这样做没有问题:
Now I can do this with no problem:
d = Dummy()
d.foo()
d.bar()
我想知道什么是最好的方法来做这个类属性是一个常规变量(例如字符串),而不是一个函数?如果我有这段代码:
What I'm wondering is what is the best way to do this with a class attribute that is a regular variable (e.g. a string) rather than a function? If I had this piece of code:
d = Dummy()
print d.x
print d.xValue
我想要 dx
和 d.xValue
到始终打印同样的内容。如果 dx
更改,它也应该更改 d.xValue
(反之亦然)。
I want d.x
and d.xValue
to ALWAYS print the same thing. If d.x
changes, it should change d.xValue
also (and vice-versa).
我可以想到很多方法来做到这一点,但没有一个看起来像我想要的那么光滑:
I can think of a number of ways to do this, but none of them seem as smooth as I'd like:
- 编写自定义注释
- 使用
@property
注释并与设置器混淆 - 覆盖
__ setattr __
类函数
- Write a custom annotation
- Use the
@property
annotation and mess with the setter - Override the
__setattr__
class functions
是最好的?还是有另一种方式?我不禁感到,如果它很容易使函数的别名,它应该是任意变量一样容易...
Which of these ways is best? Or is there another way? I can't help but feel that if it's so easy to make aliases for functions, it should be just as easy for arbitrary variables...
FYI:我使用Python 2.7.x,而不是Python 3.0,所以我需要一个Python 2.7.x兼容的解决方案(虽然我会感兴趣,如果Python 3.0做一些直接解决这个需要)。
FYI: I'm using Python 2.7.x, not Python 3.0, so I need a Python 2.7.x compatible solution (though I would be interested if Python 3.0 does something to directly address this need).
谢谢!
推荐答案
您可以提供 __ setattr __
code> __ getattr __ 引用别名映射:
You can provide a __setattr__
and __getattr__
that reference an aliases map:
class Dummy(object):
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 getattr(self, name) #Causes infinite recursion on non-existent attribute
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
这篇关于如何在Python类中为非函数成员属性创建别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!