V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
geew
V2EX  ›  问与答

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

  •  
  •   geew · Aug 9, 2013 · 3860 views
    This topic created in 4656 days ago, the information mentioned may be changed or developed.
    这么一种情况
    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 replies    1970-01-01 08:00:00 +08:00
    reorx
        1
    reorx  
       Aug 9, 2013
    我只能想到用 metaclass,让所有的 classmethod 在定义时被替换成一个新的 classmethod,这个 classmethod 中执行了检查和原方法的代码。

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

    http://gist.github.com/reorx/6190610
    raquelken
        2
    raquelken  
       Aug 9, 2013
    创建一个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  
       Aug 9, 2013
    另外,你可以 pip search classproperty
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3329 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 10:45 · PVG 18:45 · LAX 03:45 · JFK 06:45
    ♥ Do have faith in what you're doing.