不希望实例看到Python @classmethod

时间:2014-12-18 22:16:26

标签: python instance class-method

我想使用@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'>>

1 个答案:

答案 0 :(得分:2)

尝试使用metaclass

class Meta(type):
    # There is *NO* @classmethod decorator here
    def my_class_method(cls):
        print "I have a class {}".format(cls)

class MyThing(object):
    __metaclass__ = Meta
    def __init__(self, this=None):
        self.this = this

这比大多数人需要或想要的更重要,所以只有你真的确定需要它才能做到这一点。大多数情况下,正常@classmethod就足够了。