Why a class when there will only be one instance?
Peter Maas
peter.maas at mplusr.de
Wed May 26 09:14:45 EDT 2004
SeeBelow at SeeBelow.Nut wrote:
> Even easier is not to make anything a class unless there will be two or
> more instances of it. I still don't get what advantage making a class
> buys for you.
To use classes even in single instance cases has some advantages:
- There is a unique way of organizing your code.
- There is an easy transition to the multiple instance case.
- It makes writing meta code (e.g. for documentation, transformation
...) easier.
- Code organisation should resemble the real world problem to be modeled
(for the sake of clarity): if emphasis is on an entity (e.g. a document)
use an object, if emphasis is on activity (e.g. computing the cosine)
use a function.
These advantages outweigh by far lexical arguments (self. takes soooo long
to type) or temporary arguments (instance count is currently = 1).
Of course this is largely a matter of taste but I am a 'burnt child'
because I had to deal with the one-instance argument in multi-developer
projects and found the defender's code quite messy. :)
> Other people have mentioned "code reuse". Again I don't see how a class
> helps to make code reusable.
Inheritance.
> I find methods in a class more difficult to reuse than simple function
> definitions. (unless there are multiple instances.)
Why? Methods are functions with an instance argument:
class person:
def tellName(self):
print self.name
>>> p = person()
>>> p.name = 'Peter'
>>> intro_c = person.tellName
>>> intro_c(p)
Peter
>>> intro_i = p.tellName
>>> intro_i()
Peter
Mit freundlichen Gruessen,
Peter Maas
--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de
-------------------------------------------------------------------
More information about the Python-list
mailing list