HomePython Page 4 - Object-Oriented Programming With Python (part 2)
Under The Microscope - Python
With the basics out of the way, this concluding article discussesmore advanced aspects of Python's OO implementation, including inheritance,destructors and overrides.
A number of built-in functions are available to help you navigate Python's classes and objects.
The most basic task involves distinguishing between classes and instances - and the type() function can help here. Take a look:
>>> type(veryBigSnake)
<type 'class'>
>>> beta = veryBigSnake("Vanessa Viper", "viper")
New snake in da house!
>>> type(beta)
<type 'instance'>
>>>
You may already be familiar with the dir() function, which
returns a list of object properties and methods - look what it says when I run it on a class
Every class also exposes the __bases__ property, which holds
the name(s) of the class(es) from which this particular class has been derived. Most of the time, this property does not contain a value; it's only useful if you're working with classes which inherit methods and properties from each other.
>>> # base class - has no ancestors
>>> veryBigSnake.__bases__
()
>>> # derived class - has base class
>>> evenBiggerSnake.__bases__
(<class snake.veryBigSnake at 80d5c08>,)
>>>
If you'd like to see the values of a specific instance's
properties, you can use the instance's __dict__ property, which returns a dictionary of name-value pairs,