Search code examples
pythoninstanceclass-method

Don't want instance to see Python @classmethod


I want to use @classmethod, but I don't want to pollute the instance's namespace with it. If I have a class method for_classes_only, how do I keep the instance from getting it?

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')

This is great:

>>> MyThing.for_classes_only()
I have a class <class '__main__.MyThing'>

This is annoying:

>>> thing.for_classes_only
<bound method type.for_classes_only of <class '__main__.MyThing'>>

Solution

  • Try using a 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
    

    This is heavier magic than most people need or want, so only do this if you're really quite sure you need it. Most of the time, a normal @classmethod is good enough.