在python中,我可以使用@classmethod装饰器向类中添加方法。是否有类似的装饰器可以将属性添加到类中?我可以更好地展示我在说什么。

class Example(object):
   the_I = 10
   def __init__( self ):
      self.an_i = 20

   @property
   def i( self ):
      return self.an_i

   def inc_i( self ):
      self.an_i += 1

   # is this even possible?
   @classproperty
   def I( cls ):
      return cls.the_I

   @classmethod
   def inc_I( cls ):
      cls.the_I += 1

e = Example()
assert e.i == 20
e.inc_i()
assert e.i == 21

assert Example.I == 10
Example.inc_I()
assert Example.I == 11

我上面使用的语法是可能的还是需要更多的东西?

我需要类属性的原因是我可以延迟加载类属性,这似乎很合理。


当前回答

以下是我的做法:

class ClassPropertyDescriptor(object):

    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        return self.fget.__get__(obj, klass)()

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        type_ = type(obj)
        return self.fset.__get__(obj, type_)(value)

    def setter(self, func):
        if not isinstance(func, (classmethod, staticmethod)):
            func = classmethod(func)
        self.fset = func
        return self

def classproperty(func):
    if not isinstance(func, (classmethod, staticmethod)):
        func = classmethod(func)

    return ClassPropertyDescriptor(func)


class Bar(object):

    _bar = 1

    @classproperty
    def bar(cls):
        return cls._bar

    @bar.setter
    def bar(cls, value):
        cls._bar = value


# test instance instantiation
foo = Bar()
assert foo.bar == 1

baz = Bar()
assert baz.bar == 1

# test static variable
baz.bar = 5
assert foo.bar == 5

# test setting variable on the class
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50

当我们调用Bar时,setter没有工作。酒吧,因为我们在打电话 TypeOfBar.bar。__set__,不是Bar.bar.__set__。

添加元类定义可以解决这个问题:

class ClassPropertyMetaClass(type):
    def __setattr__(self, key, value):
        if key in self.__dict__:
            obj = self.__dict__.get(key)
        if obj and type(obj) is ClassPropertyDescriptor:
            return obj.__set__(self, value)

        return super(ClassPropertyMetaClass, self).__setattr__(key, value)

# and update class define:
#     class Bar(object):
#        __metaclass__ = ClassPropertyMetaClass
#        _bar = 1

# and update ClassPropertyDescriptor.__set__
#    def __set__(self, obj, value):
#       if not self.fset:
#           raise AttributeError("can't set attribute")
#       if inspect.isclass(obj):
#           type_ = obj
#           obj = None
#       else:
#           type_ = type(obj)
#       return self.fset.__get__(obj, type_)(value)

现在一切都会好起来的。

其他回答

如果你使用Django,它有一个内置的@classproperty装饰器。

from django.utils.decorators import classproperty

对于Django 4,使用:

from django.utils.functional import classproperty

我认为您可以通过元类来实现这一点。因为元类可以像类的类(如果有意义的话)。我知道你可以给元类赋一个__call__()方法来覆盖调用类MyClass()。我想知道在元类上使用属性装饰器的操作是否类似。

哇,真管用:

class MetaClass(type):    
    def getfoo(self):
        return self._foo
    foo = property(getfoo)
    
    @property
    def bar(self):
        return self._bar
    
class MyClass(object):
    __metaclass__ = MetaClass
    _foo = 'abc'
    _bar = 'def'
    
print MyClass.foo
print MyClass.bar

注意:这是在Python 2.7中。Python 3+使用不同的技术来声明元类。使用:class MyClass(metaclass= metaclass):,删除__metaclass__,其余部分相同。

如果你只需要惰性加载,那么你可以只需要一个类初始化方法。

EXAMPLE_SET = False
class Example(object):
   @classmethod 
   def initclass(cls):
       global EXAMPLE_SET 
       if EXAMPLE_SET: return
       cls.the_I = 'ok'
       EXAMPLE_SET = True

   def __init__( self ):
      Example.initclass()
      self.an_i = 20

try:
    print Example.the_I
except AttributeError:
    print 'ok class not "loaded"'
foo = Example()
print foo.the_I
print Example.the_I

但是元类方法看起来更简洁,行为更可预测。

也许您正在寻找的是单例设计模式。关于在Python中实现共享状态,有一个很好的SO QA。

def _create_type(meta, name, attrs):
    type_name = f'{name}Type'
    type_attrs = {}
    for k, v in attrs.items():
        if type(v) is _ClassPropertyDescriptor:
            type_attrs[k] = v
    return type(type_name, (meta,), type_attrs)


class ClassPropertyType(type):
    def __new__(meta, name, bases, attrs):
        Type = _create_type(meta, name, attrs)
        cls = super().__new__(meta, name, bases, attrs)
        cls.__class__ = Type
        return cls


class _ClassPropertyDescriptor(object):
    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, owner):
        if self in obj.__dict__.values():
            return self.fget(obj)
        return self.fget(owner)

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        return self.fset(obj, value)

    def setter(self, func):
        self.fset = func
        return self


def classproperty(func):
    return _ClassPropertyDescriptor(func)



class Bar(metaclass=ClassPropertyType):
    __bar = 1

    @classproperty
    def bar(cls):
        return cls.__bar

    @bar.setter
    def bar(cls, value):
        cls.__bar = value

bar = Bar()
assert Bar.bar==1
Bar.bar=2
assert bar.bar==2
nbar = Bar()
assert nbar.bar==2

[基于python 3.4编写的答案;元类语法在2中有所不同,但我认为该技术仍然有效]

你可以通过元类来实现。Dappawit几乎可以,但我认为它有一个缺陷:

class MetaFoo(type):
    @property
    def thingy(cls):
        return cls._thingy

class Foo(object, metaclass=MetaFoo):
    _thingy = 23

这让你在Foo上获得一个类属性,但有一个问题…

print("Foo.thingy is {}".format(Foo.thingy))
# Foo.thingy is 23
# Yay, the classmethod-property is working as intended!
foo = Foo()
if hasattr(foo, "thingy"):
    print("Foo().thingy is {}".format(foo.thingy))
else:
    print("Foo instance has no attribute 'thingy'")
# Foo instance has no attribute 'thingy'
# Wha....?

这到底是怎么回事?为什么我不能从实例中到达class属性?

在找到我所相信的答案之前,我在这个问题上苦苦思索了很久。Python @properties是描述符的子集,并且,从描述符文档(强调我的):

属性访问的默认行为是获取、设置或删除 属性。例如,a.x有一个查找链 从a.__dict__['x']开始,然后输入(a)。__dict__['x'],并继续 通过类型(a)的基类,不包括元类。

因此方法解析顺序不包括我们的类属性(或元类中定义的任何其他属性)。有可能让内置属性装饰器的子类表现不同,但是(需要引用)我在谷歌上得到的印象是,开发人员有一个很好的理由(我不明白)这样做。

这并不意味着我们不走运;我们可以很好地访问类本身的属性……我们可以从实例中的type(self)中获取类,我们可以使用它来创建@property dispatchers:

class Foo(object, metaclass=MetaFoo):
    _thingy = 23

    @property
    def thingy(self):
        return type(self).thingy

现在Foo()。Thingy对类和实例都像预期的那样工作!如果派生类替换了它的底层_thingy(这是最初让我进行搜索的用例),它也将继续做正确的事情。

这对我来说不是百分之百的满意——必须在元类和对象类中进行设置,感觉它违反了DRY原则。但后者只是一个单行调度器;我基本同意它的存在,如果你真的想,你也可以把它压缩成。