Python Classes

dieter dieter at handshake.de
Tue Aug 5 02:37:11 EDT 2014


Shubham Tomar <tomarshubham24 at gmail.com> writes:
> Python is the first programming language that I'm learning.
> I'm confused by the idea of classes and intimidated by syntax defining
> classes. I understand that you define classes to have re-usable methods and
> procedures, but, don't functions serve the same purpose.

As often, you may have building blocks at various levels.
Thinks of a house - you can build it from individual stones or
have large prefabricated parts.
Something similar is true with functions and classes.

A function is a building block at some level.
However, often, you deal not with individual unrelated functions but
with a set of related functions designed together.

In simple cases, those functions can be collected in a library or
a module (Python's "math" module is such an example - containing
many interesting "mathematical" functions).

In other (slightly more complicated) cases, the relation between
the functions is that they all work on the same "object".

Those "object"s can be almost anything. An example would be
a "window" on your desktop screen. It can be closed, resized, moved around, ...
Or a "geometric object" in a drawing application - with operations
"delete", "move", "resized", "extend", ...

In those cases, it can be helpful to view the object (its data)
and the functions operating on it (such as "move", "resize", ...)
as a higher level building block -- and this leads to classes.

A "class" (in Python) is a collection of related functions (called
"method"s) and potentially data definitions (this part is quite
weak for Python classes; unlike in other languages, the data part
of a class is not stated explicitely at the top class level, but
usually indirectly in the so called constructor ("__init__")).
Most of these functions operate on the same data. Data and functions
together are called an "object" and the "class" defines a set
of objects of some common kind: "window"s, "date"s, "server"s,
"geometric object"s ...


This higher level building block can facilitate the construction
of many applications.




More information about the Python-list mailing list