类变量的setter

问题描述 投票:3回答:3

我在名为foo.py的模块中有一个简单的类:

class Foo
    foo = 1

我导入到其他模块(bar.pybaz.py)并在这些其他模块中更改类变量foo,例如:

# bar.py

from foo import Foo
print(Foo.foo) # should print 1.
Foo.foo = 2

# baz.py

from foo import Foo

print(Foo.foo) # should print 2.
Foo.foo = 3

但是,Foo.foo的更改应该在设置之前进行检查。因此,我目前在Foo中使用setter方法:

# foo.py

@classmethod
def set_foo(cls, new_foo):
    # do some checks on the supplied new_foo, then set foo.
    cls.foo = new_foo

这是设置类变量的pythonic方法吗?或者有更好的方法(类似于实例变量的@property a@a.setter声明)?我希望类变量foo在这些其他模块中导入Foo时仍然存在,并且实际上并不想创建Foo的实例,因为它更像是一个类的东西。

谢谢SO ;-)

python class attributes setter
3个回答
1
投票

如果你不介意一点魔法,可以通过使用描述符协议相对合理地完成。

class FooDescriptor:

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return obj._foo

    def __set__(self, obj, value):
        if not isinstance(obj, type):
            # disable instance name shadowing for sanity's sake
            raise AttributeError("this attribute should be set on the class object")
        obj._foo = value + "!!"


class FooMeta(type):

    foo = FooDescriptor()

    def __new__(cls, clsname, bases, namespace):
        # pluck the "foo" attr out of the class namespace,
        # and swap in our descriptor in its place
        namespace["_foo"] = namespace.pop("foo", "(default foo val)")
        namespace["foo"] = FooMeta.foo
        return type.__new__(cls, clsname, bases, namespace)

构造类Foo时,这将用正常的声明方式定义的foo类属性替换为数据描述符(以提供自定义的getter和setter)。我们将在Foo._foo中存储原始的“非托管”值。

演示:

>>> class Foo(metaclass=FooMeta): 
...     foo = "foo0" 
... 
>>> obj = Foo() 
>>> obj.foo  # accessible from instance, like a class attr
'foo0'
>>> Foo.foo  # accessible from class
'foo0'
>>> Foo.foo = "foo1"  # setattr has magic, this will add exclams
>>> obj.foo
'foo1!!'
>>> Foo.foo
'foo1!!'
>>> vars(obj)  # still no instance attributes
{}
>>> type(Foo).foo  # who does the trick?
<__main__.FooDescriptor at 0xcafef00d>
>>> obj.foo = "boom"  # prevent name shadowing (optional!)
AttributeError: this attribute should be set on the class object

0
投票

如果您计划继承Foo,请注意classmethod将修改调用实例类的属性。

class Base:

    class_variable = 'base'

    @classmethod
    def set_cvar(cls, value):
        cls.class_variable = value

class Derived(Base):

    pass

Derived.set_cvar('derived')
print(Base.class_variable)
print(Derived.class_variable)

输出:

base
derived

这可能(可能会)或者可能不是你想要的。另一种方法是改为使用staticmethod并明确命名您的类。

但总的来说,我认为这是一个很好的方法。


-2
投票

我认为'pythonic方式',如果有的话,使用a.setter,使用_格式:

@property
def bar(self):
    return self._bar

@bar.setter
def environment(self, bar):
    # do some checks on the supplied bar, then set
    self._bar = bar

这样_bar就是'私有',当你想要设置它时,你可以在代码中“禁止”。

© www.soinside.com 2019 - 2024. All rights reserved.