From 5391804ac5f8edbeaa4a4f9f512e6b6b26949772 Mon Sep 17 00:00:00 2001 From: gwen Date: Thu, 4 Jun 2015 09:58:51 +0200 Subject: [PATCH] ajout de doc sur les classes et les objets --- python/formation/classes.txt | 118 +++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/python/formation/classes.txt b/python/formation/classes.txt index 5f4b5bc..085c9d6 100644 --- a/python/formation/classes.txt +++ b/python/formation/classes.txt @@ -72,6 +72,124 @@ possibilité en python d'héritage multiple:: class A(B, C): pass +attribut d'objets et de classes +---------------------------------- + +>>> o = object() +>>> o + +>>> class C(object): pass +... +>>> class C: pass +... +>>> c = C() +>>> c.a = 3 +>>> c.a +3 +>>> vars(c) +{'a': 3} +>>> c.__dict__ +{'a': 3} +>>> C.__dict__ +{'__module__': '__main__', '__doc__': None} +>>> C.c = 5 +>>> C.__dict__ +{'c': 5, '__module__': '__main__', '__doc__': None} +>>> c.c +5 +>>> c.z = 3 +>>> c.z +3 +>>> c.__dict__ +{'a': 3, 'z': 3} +>>> C.__dict__ +{'c': 5, '__module__': '__main__', '__doc__': None} +>>> class MaKlass: +... def unefonction(self, x): +... print x +... +>>> MaKlass.__dict__ +{'__module__': '__main__', '__doc__': None, 'unefonction': } +>>> k = MaKlass() +>>> k.__dict__ +{} +>>> def autrefonc(self, x) + File "", line 1 + def autrefonc(self, x) + ^ +SyntaxError: invalid syntax +>>> def autrefonc(self, x): +... print x +... +>>> k.autrefonc = autrefonc +>>> k.__dict__ +{'autrefonc': } +>>> MaKlass.__dict__ +{'__module__': '__main__', '__doc__': None, 'unefonction': } +>>> MaKlass.unefonction(k, "toto") +toto +>>> k.unefonction("toto") +toto +>>> k.__dict__ +{'autrefonc': } +>>> MaKlass.toto = "test" +>>> k.__dict__ +{'autrefonc': } +>>> k.toto +'test' +>>> + + +le __dict__ avec l'héritage de classe +------------------------------------------- + + +>>> class A(object): pass +... +>>> A.__dict__ +dict_proxy({'__dict__': , '__module__': '__main__', '__weakref__': , '__doc__': None}) +>>> class B(A): +... b = 3 +... +>>> class C(B): +... c = 2 +... +>>> c = C() +>>> o = C() +>>> o.__dict__ +{} +>>> o.c +2 +>>> o.b +3 +>>> o.__class__ + +>>> o.__class__.__dict__ +dict_proxy({'__module__': '__main__', 'c': 2, '__doc__': None}) +>>> + + +method resolution object +----------------------------- + +>>> class A(object): pass +... +>>> A.__mro__ +(, ) +>>> class B(A): pass +... +>>> B.__mro__ +(, , ) +>>> class C(A, B): pass +... +Traceback (most recent call last): + File "", line 1, in +TypeError: Error when calling the metaclass bases + Cannot create a consistent method resolution +order (MRO) for bases A, B +>>> + + introspection contre encapsulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~