获取Python中正在访问、设置或删除的@property的名称
在Python中,是否可以在函数中获取当前正在访问、修改以删除的属性的名称?例如,我有一段代码,里面有一些伪代码:获取Python中正在访问、设置或删除的@property的名称,python,properties,Python,Properties,在Python中,是否可以在函数中获取当前正在访问、修改以删除的属性的名称?例如,我有一段代码,里面有一些伪代码: class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" prop = get_current_property() #prop is set to 'x'
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
prop = get_current_property() #prop is set to 'x'
return self._x
@x.setter
def x(self):
"""I'm the 'x' property."""
prop = get_current_property() #prop is set to 'x'
return self._x
@property
def y(self):
"""I'm the 'x' property."""
prop = get_current_property() #prop is set to 'y'
return self._x
因此这里的伪代码是
get\u current\u property()
,它应该在每个属性的getter、setter和deleter方法内部工作。有办法吗 所以,没有办法让它轻松性感。只有肮脏的魔法,我的朋友
import inspect
class A(object):
@property
def b(self):
print inspect.stack()[0][3]
A().b
会给你想要的结果,但只有在你无法处理事情的情况下,你才应该这样做
顺便说一句,您可以尝试制作一个装饰器,它将接受一个函数,接受它的\uuuu名称\uuuu
并将其作为参数发送
以下是idea的实施:
def named_property(func):
return property(lambda *a, **kwa: func(*a, fname=func.__name__, **kwa))
class A(object):
@named_property
def b(self, fname):
print fname
A().b # will print 'b'
正如@Martijn Pieters所说,该方法没有直接的方法来获取对自身的引用 我试图理解为什么属性定义(由您编写)还不知道它自己的名称。我猜您希望这样做,以便可以通过编程方式创建一组属性,而无需对每个属性进行单独的显式定义 尝试以下方法动态构建新类,同时从列表中创建其某些属性:
def make_getter_setter(name):
# this function uses an implicit closure to "freeze" the local value of name
# within the scope of the getter/setter functions
def getter(self):
return name
def setter(self):
pass # your original code doesn't make clear that the setter should actually do anything
return getter, setter
class C(object):
def __init__(self):
# dictionary to store the values of the properties
# this doesn't do anything now, but I presume you'll want to allow
# setting the properties later, and you'll need somewhere to store
# their values
self._properties = {}
for name in ('spam', 'eggs', 'ham'):
getter, setter = make_getter_setter(name)
setattr(C, name, property(getter, setter, doc="I'm the '%s' property" % name))
foo = C()
print foo.eggs, foo.ham # shows their values
help(foo) # shows their doc strings
相关:不,你不能,不是真的。函数对象本身没有引用,更不用说属性对象了。人们提出了各种内省技巧,但底线是:只需将名称放入局部变量中。