Transforming a class into a string


Interesting right?
If you read this amazing tutorial by lionaneesh, you will understand why I posted this brain-boggling code.

About the Author

I love Python!
I often play with D and C#.

class TurnIntoString(type):
    def __new__(metacls, clsN, bases, clsdict):
        return "{0} from {1}.".format(clsdict.get('msg'),

class MyMessage(object):
    __metaclass__ = TurnIntoString
    msg = "Hello World"

print MyMessage
print MyMessage.upper()
print type(MyMessage)
print MyMessage[::-1]

#What? MyMessage, which is obviously a
#class, is now a string?
    a = MyMessage() #doesn't even behave like a class anymore
    print "It's no longer a class, but a string."

Basically, a metaclass is the class of a class.
So if you want to change a class in some way,
you can do that through metaclasses.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.