Object-Oriented Programming With Python (part 2) - Under The Microscope
(Page 4 of 5 )
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
>>> dir(veryBigSnake)
['__del__', '__doc__', '__init__', '__module__', 'set_snake_name',
'set_snake_type', 'who_am_i']
>>>
and on an object of that class.
>>> dir(beta)
['name', 'type']
>>>
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,
>>> beta.__dict__
{'name': 'Vanessa Viper', 'type': 'viper'}
>>>
while the corresponding __class__ property identifies the
class from which this instance was spawned.
>>> beta.__class__
<class snake.veryBigSnake at 80cda20>
>>>
Next: Chaos And Destruction >>
More Python Articles
More By icarus, (c) Melonfire