Skip to content

Instantly share code, notes, and snippets.

@florentin
Last active October 5, 2017 12:48
Show Gist options
  • Save florentin/4c210918a9a00443aeac to your computer and use it in GitHub Desktop.
Save florentin/4c210918a9a00443aeac to your computer and use it in GitHub Desktop.
Python method resolution demo
class Desc(object):
def __init__(self, msg):
self.msg = msg
def __get__(self, instance, owner=None):
return "{0}: {1}".format(self.typ, self.msg)
class NonDesc(Desc):
# non-data descriptor
typ = 'NonDesc'
class DataDesc(Desc):
# data descriptor
typ = 'DataDesc'
def __set__(self, instance, value):
pass
def __delete__(self, instance):
pass
class M(type):
x = 'x from M'
y = NonDesc('y from cls M')
z = DataDesc('z from cls M')
def __getattr__(self, name):
return "getattr M {0}".format(name)
class A(object):
#t = 't from A'
#u = NonDesc('u from cls A')
#v = DataDesc('v from cls A')
x = 'x from A'
y = NonDesc('y from cls A')
z = DataDesc('z from cls A')
class B(A):
"""
metaclass is M
"""
__metaclass__ = M
class C(B):
"""
metaclass is inherited from C
"""
def __getattr__(self, name):
return "getattr C: {0}".format(name)
c = C()
print '******'
print 'c.__class__', c.__class__
print 'c.__class__.__getattribute__', c.__class__.__getattribute__
print 'c.__class__.__mro__', c.__class__.__mro__
print '******'
print 'c.x', c.x
print 'c.y', c.y
print 'c.z', c.z
print 'c.nope', c.nope
c.t = 't from obj c'
c.u = NonDesc('u from obj c')
c.v = DataDesc('v from obj c')
c.x = 'x from obj c'
c.y = NonDesc('y from obj c')
c.z = DataDesc('z from obj c')
print '******'
print 'c.t', c.t
print 'c.u', c.u
print 'c.v', c.v
print 'c.x', c.x
print 'c.y', c.y
print 'c.z', c.z
print '******'
print "C.x", C.x
print "C.y", C.y
print "C.z", C.z
print "C.nope", C.nope
C.t = 't from obj C'
C.u = NonDesc('u from obj C')
C.v = DataDesc('v from obj C')
C.x = 'x from obj C'
C.y = NonDesc('y from obj C')
C.z = DataDesc('z from obj C')
print '******'
print "C.t", C.t
print "C.u", C.u
print "C.v", C.v
print "C.x", C.x
print "C.y", C.y
print "C.z", C.z
print "C.nope", C.nope
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment