V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
geew
V2EX  ›  问与答

[python]python使用类方法时默认调用

  •  
  •   geew · 2013-08-09 09:47:57 +08:00 · 3396 次点击
    这是一个创建于 3963 天前的主题,其中的信息可能已经有所发展或是发生改变。
    这么一种情况
    class A:
    _name = None

    @classmethod
    def f(cls):
    assert cls._name is no None


    使用f方法的话可以直接A.f()来进行调用, 子类中也可以通过super(Child, cls).f()来进行调用,
    但我想在调用f之前检查cls._name, 又不想在每个classmethod中都这么写:
    @classmethod
    def f(cls):
    if cls._name is None:
    cls._name = 'something'

    有什么好的方法能在使用类方法时默认执行某个函数呢, 修饰器貌似大了点吧, 谢谢
    3 条回复    1970-01-01 08:00:00 +08:00
    reorx
        1
    reorx  
       2013-08-09 10:11:04 +08:00
    我只能想到用 metaclass,让所有的 classmethod 在定义时被替换成一个新的 classmethod,这个 classmethod 中执行了检查和原方法的代码。

    http://gist.github.com/6190610.git

    http://gist.github.com/reorx/6190610
    raquelken
        2
    raquelken  
       2013-08-09 11:07:52 +08:00
    创建一个classproperty

    class classproperty(object):
    def __init__(self, clsattr):
    self.clsattr = classmethod(clsattr)
    def __get__(self, obj, objtype):
    return self.clsattr.__get__(obj, objtype)()

    class A(object):

    _name = None

    @classproperty
    def name(cls):
    if not cls._name:
    cls._name = 'something'
    return cls._name

    @classmethod
    def f(cls):
    print 'f', cls.name

    @classmethod
    def ff(cls):
    print 'ff', cls.name

    if __name__ == '__main__':
    A.f()
    A.name = 'something change'
    A.ff()
    raquelken
        3
    raquelken  
       2013-08-09 11:08:25 +08:00
    另外,你可以 pip search classproperty
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1035 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:24 · PVG 03:24 · LAX 12:24 · JFK 15:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.