python objects
python objects
Class objects support two kinds of operations: attribute references and instantiation.
Attribute references use the standard syntax used for all attribute references in
Python: obj.name. Valid attribute names are all the names that were in the class’s
namespace when the class object was created. So, if the class definition looked like
this:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
then MyClass.i and MyClass.f are valid attribute references, returning an integer and a
function object, respectively. Class attributes can also be assigned to, so you can
change the value of MyClass.i by assignment. __doc__ is also a valid attribute, return-
ing the docstring belonging to the class: "A simple example class".
Class instantiation uses function notation. Just pretend that the class object is a pa-
rameterless function that returns a new instance of the class. For example (assuming
the above class):
x = MyClass()
creates a new instance of the class and assigns this object to the local variable x.
The instantiation operation (“calling” a class object) creates an empty object. Many
classes like to create objects with instances customized to a specific initial state.
Therefore a class may define a special method named __init__(), like this:
def __init__(self):
self.data = []
x = MyClass()
Of course, the __init__() method may have arguments for greater flexibility. In that
case, arguments given to the class instantiation operator are passed on to __init__().
For example,
>>>
Now what can we do with instance objects? The only operations understood by in-
stance objects are attribute references. There are two kinds of valid attribute names:
data attributes and methods.
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
The other kind of instance attribute reference is a method. A method is a function that
“belongs to” an object.
Valid method names of an instance object depend on its class. By definition, all at-
tributes of a class that are function objects define corresponding methods of its in-
stances. So in our example, x.f is a valid method reference, since MyClass.f is a func-
tion, but x.i is not, since MyClass.i is not. But x.f is not the same thing as My-
Class.f — it is a method object, not a function object.