# mromagic.py
class A(object):
def a_method(self):
print("A")
class B(object):
def b_method(self):
print("B")
class MROMagicMeta(type):
def mro(cls):
return (cls, B, object)
class C(A, metaclass=MROMagicMeta):
def c_method(self):
print("C")
Now let's play with this a little:
>>> import mromagic
>>> mycls = mromagic.C()
>>> mycls
<mromagic.C object at 0x622890>
>>> mycls.c_method()
C
>>> mycls.a_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'a_method'
>>> mycls.b_method()
B
>>> type(mycls).__mro__
(<class 'mromagic.C'>, <class 'mromagic.B'>, <class 'object'>)
>>> type(mycls).__bases__
(<class 'mromagic.A'>,)
How does this work? By overriding mro() on the a metaclass we can define a custom __mro__ for our class. Python will then traverse it instead of the default implementation, which is provided by type.mro().
6 comments:
Python 2.5.1 does not accept the metaclass= syntax in the base class description at compile time, and does not accept type as a base class at runtime (since no argument is provided to the constructor).
@Anon I said I was using 3.0 syntax; you just use the 2.x metaclass syntax for 2.x. I'm not sure why you think you can't inherit from type in 2.5, since you can...
Nice example thank you very much not sure I need to use it often but these quirks of python are nice to know.
Thanks, very interesting
The esay generator is a powerful tool that streamlines the essay writing process. By utilizing advanced algorithms and language models, the esay generator helps users generate well-structured and coherent essays. It simplifies the task of crafting arguments and organizing ideas, enabling writers to focus on the content itself. The esay generator is a valuable resource for those seeking to save time and produce high-quality essays effortlessly.
This article on MRO Magic is truly enlightening! It's fascinating to see how Maintenance, Repair, and Overhaul processes are evolving with technology. The insights into streamlining operations and enhancing efficiency really resonate, especially in today’s fast-paced industry. I'm particularly interested in how these advancements can reduce downtime and improve safety. Looking forward to seeing more innovations in this field!"
Digital Marketing Course In Hyderabad
Post a Comment