Transforming a class into a string

jcao219 0 Tallied Votes 155 Views Share

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

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

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?
try:
    a = MyMessage() #doesn't even behave like a class anymore
except:
    print "It's no longer a class, but a string."
jcao219 18 Posting Pro in Training

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.