在Python3.6中,我可以使用__set_name__
钩子来获取描述符的类属性名。如何在python2.x中实现这一点?在
以下是在Python 3.6中运行良好的代码:
class IntField:
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError('expecting integer')
instance.__dict__[self.name] = value
def __set_name__(self, owner, name):
self.name = name
class Example:
a = IntField()
有各种不同程度的解决方案。我总是喜欢用类装饰器。在
你可以这样使用它:
^{pr2}$演示:
请确保在Python2.7中显式地从
object
子类,这让我在起草这个答案的第一个版本时遇到了麻烦。在您可能正在寻找元类,有了它,您可以在类创建时处理类属性。在
输出:
^{pr2}$如果需要在创建类之前更改类,则需要在元类中重写}。有关此主题的详细信息,请参阅此答案:Is there any reason to choose __new__ over __init__ when defining a metaclass?
__new__
,而不是{相关问题 更多 >
编程相关推荐