我想使用@classmethod
,但我不想用它污染实例的命名空间。如果我有一个类方法for_classes_only
,如何防止实例获取它?你知道吗
class MyThing(object):
def __init__(self, this=None):
self.this = this
@classmethod
def for_classes_only(cls):
print "I have a class {}".format(cls)
thing = MyThing(this='that')
这很好:
>>> MyThing.for_classes_only()
I have a class <class '__main__.MyThing'>
这很烦人:
>>> thing.for_classes_only
<bound method type.for_classes_only of <class '__main__.MyThing'>>
尝试使用metaclass:
这是比大多数人需要或想要的更重的魔法,所以只有当你真的很确定你需要它的时候才这么做。大多数时候,一个正常的
@classmethod
就足够了。你知道吗相关问题 更多 >
编程相关推荐