ajout de doc sur les méta classes

This commit is contained in:
gwen 2015-06-04 10:10:58 +02:00
parent 5391804ac5
commit d3fedded5e
1 changed files with 70 additions and 0 deletions

View File

@ -380,3 +380,73 @@ autre exemple : les méthodes statiques
... # do stuff here ... # do stuff here
métaclasses
-----------------
>>> class A:
... pass
...
>>> type(A)
<type 'classobj'>
>>> class B(object): pass
...
>>> type(B)
<type 'type'>
>>> help(type)
>>> C = type('C', (), {})
>>> C
<class '__main__.C'>
>>>
>>> type(object)
<type 'type'>
>>> type(type)
<type 'type'>
>>> isinstance(type, object)
True
>>> isinstance(object, type)
True
>>>
::
class MaMetaClasse(type):
"""Exemple d'une métaclasse."""
def __new__(metacls, nom, bases, dict):
"""Création de notre classe."""
print("On crée la classe {}".format(nom))
return type.__new__(metacls, nom, bases, dict)
class MaClasse(object):
__metaclass__ = MaMetaClasse
exemple : forcer l'implémentation d'un singleton avec les métaclasses
::
class Singleton(type):
instance = None
def __call__(cls, *args, **kw):
if not cls.instance:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class ASingleton(object):
__metaclass__ = Singleton
a = ASingleton()
b = ASingleton()
assert a is b
print(a.__class__.__name__, b.__class__.__name__)
class BSingleton(object):
__metaclass__ = Singleton
c = BSingleton()
d = BSingleton()
assert c is d
print(c.__class__.__name__, d.__class__.__name__)
assert c is not a