Metaclasses - magic functions

Mr. Wrobel mr at e-wrobel.pl
Fri Dec 23 14:20:41 EST 2016


W dniu 23.12.2016 o 15:14, Ian Kelly pisze:
(...)
>
>     cls.added_in_init = 'test'
>

Man, you are awsome genius! Finally somebody was able to explain me what 
is the power of __new__ and difference between __init__ !!!

So what I wanted to achieve was adding some new attributes to the class 
instances (objects) like this:

########
#!/usr/bin/env python

class MetaClass(type):
     # __init__ manipulation:

     def __init__(cls, name, bases, dct):
         cls.added_in_init = 'test'
         super(MetaClass, cls).__init__(name, bases, dct)

class BaseClass(object):
     __metaclass__ = MetaClass

class NewBaseClass(BaseClass):
     def __init__(self):
         self.inst_attr = self.added_in_init


print("Lets print attributes added in __init__ in base classes:")


b = NewBaseClass()
print(b.added_in_init)

print(b.inst_attr)
########

And finally it works!

Man I owe you a galaxy of thanks, because I was so frustrated! The 
examples taken from internet never explained me it in so clearly like 
you did!

Really, really thank you!!!


More information about the Python-list mailing list