4

在 Python 3.6 中,我可以使用__set_name__钩子来获取描述符的类属性名称。如何在 python 2.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()
4

2 回答 2

4

您可能正在寻找元类,使用它您可以在类创建时处理类属性。

class FooDescriptor(object):
    def __get__(self, obj, objtype):
        print('calling getter')

class FooMeta(type):
    def __init__(cls, name, bases, attrs):
        for k, v in attrs.iteritems():
            if issubclass(type(v), FooDescriptor):
                print('FooMeta.__init__, attribute name is "{}"'.format(k))

class Foo(object):
    __metaclass__ = FooMeta
    foo = FooDescriptor()


f = Foo()
f.foo

输出:

FooMeta.__init__, attribute name is "foo"
calling getter

如果您需要在创建类之前更改它,您需要覆盖__new__而不是__init__在您的元类中。有关此主题的更多信息,请参阅此答案:在定义元类时,是否有任何理由选择 __new__ 而不是 __init__?

于 2018-11-10T18:08:46.633 回答
1

有各种不同程度的hackish的解决方案。我一直喜欢为此使用类装饰器。

class IntField(object):
    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 with_intfields(*names):
    def with_concrete_intfields(cls):
        for name in names:
            field = IntField()
            field.name = name
            setattr(cls, name, field)
        return cls
    return with_concrete_intfields

你可以像这样使用它:

@with_intfields('a', 'b')
class Example(object):
    pass

e = Example()

演示:

$ python2.7 -i clsdec.py
>>> [x for x in vars(Example) if not x.startswith('_')]
['a', 'b']
>>> Example.a.name
'a'
>>> e.a = 3
>>> e.b = 'test'
[...]
ValueError: expecting integer

确保从objectPython 2.7 中显式子类化,当我起草这个答案的第一个版本时,这让我大吃一惊。

于 2018-11-10T17:55:59.293 回答