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

2013-08-09 09:47:57 +08:00
 geew
这么一种情况
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'

有什么好的方法能在使用类方法时默认执行某个函数呢, 修饰器貌似大了点吧, 谢谢
3429 次点击
所在节点    问与答
3 条回复
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
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
2013-08-09 11:08:25 +08:00
另外,你可以 pip search classproperty

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/78520

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX