An object is an instance (or not)?

Gregory Ewing greg.ewing at canterbury.ac.nz
Wed Jan 28 11:33:26 CET 2015


Mario Figueiredo wrote:
> An instance of an object is capable of doing so, per its 
> class definitions. Whereas a Python class object is not.
> 
>     >>> class Master:
>             def func(self):
>                 pass
> 
>     >>> class Sub(Master):
>             pass
> 
>     >>> Sub.func()
>     TypeError: func() missing 1 required positional argument: 'self'

But Sub is not an *instance* of Master here, it's
a *subclass* of Master, which is quite a different
thing:

 >>> Sub.__class__
<class 'type'>

To make Sub be an *instance* of Master, you need to
do this. (NOTE: This is Python 3 syntax; the same
thing can be done in Python 2, but the syntax is
slightly different.)

 >>> class Master(type):
...  def func(self):
...   print("func of", self, "called")
...
 >>> class Sub(metaclass = Master):
...  pass
...
 >>> Sub.__class__
<class '__main__.Master'>
 >>> Sub.func()
func of <class '__main__.Sub'> called

So, you see, Python classes *can* participate in OOP
just as fully as any other object. You just need to
know how to do it correctly.

-- 
Greg



More information about the Python-list mailing list