On 8/4/2014 6:44 PM, John Gordon wrote:
In <mailman.12627.1407141661.18130.python-l...@python.org> Shubham Tomar
<tomarshubha...@gmail.com> writes:
classes. I understand that you define classes to have re-usable methods and
procedures, but, don't functions serve the same purpose.
Can someone please explain the idea of classes
If a function simply accepts some data, does some calculations on that
data and then returns a value, then you don't need classes at all. An
example of this might be the square-root function: pass it any number
and it calculates and returns the square root with no other data needed.
But classes do come in handy for other sorts of uses. One classic example
is employees at a company. Each employee has a name, ID number, salary,
date of hire, home address, etc.
You can create an Employee class to store those data items along with
methods to manipulate those data items in interesting ways. The data
items are specific to each separate Employee object, and the methods are
shared among the entire class.
In simple cases like that, functions could do very well by including a
little bundle of data (probably a dict) as one of the parameters for
each related function. Classes help here by organizing the functions
into namespaces, and allowing very convenient and explicit syntax for
creating objects and using attributes.
In addition, classes provide hooks into almost all of Python's syntax
and operations, with special methods like __init__, __add__, etc. If you
want your employees to be comparable using the <, >, == you need to use
classes.
Classes provide a means for objects to be related, substitutable, and
interdependent, using inheritance.
Properties work only with classes and provide a convenient way to
customize attribute retrieval and setting without forcing a change in
the syntax required for usage.
Classes can be constructed dynamically using metaclasses.
Some of these things can be emulated using just functions and
mappings--it's what C programmers do--but most of classes in Python can
do requires language support.
--
Neil Cerutti
--
https://mail.python.org/mailman/listinfo/python-list