Trying to understand Python objects

John Henry john106henry at hotmail.com
Tue Nov 21 18:17:05 EST 2006


classes are not functions.  They are a "thing".

A simple example:

class pet(object):

	def __init__(self):
		self.myLegs=self._SetNumberOfLegs()

	def _SetNumberOfLegs(self):
		return 0

	def HowManyLegsDoYouHave(self):
		print self.myLegs

class cat(pet):

	def _SetNumberOfLegs(self):
		return 4

class rabbit(pet):

	def _SetNumberOfLegs(self):
		return 2

class fish(pet):
	pass

myPets=[cat(), fish(), rabbit()]

for pet in myPets:
	pet.HowManyLegsDoYouHave()


In the above example, both cat and rabbit has legs and fish?  Not
normally.  :=)

walterbyrd wrote:
> Reading "Think Like a Computer Scientist" I am not sure I understand
> the way it describes the way objects work with Python.
>
> 1) Can attributes can added just anywhere? I create an object called
> point, then I can add attributes any time, and at any place in the
> program?
>
> 2) Are classes typically created like this:
>
> class Point:
>   pass
>
> Then attributes are added at some other time?
>
> 3) What is with the __underscores__ ??
>
> 4) Are parameters passed to an class definition?
>
> class Whatever(params):
>    pass
>
> I sort-of understand the way objects work with PHP. With PHP, the
> classes are defined in one place - sort of like a function. To me, that
> makes more sense.




More information about the Python-list mailing list