Confused about class behavior

Stephen Hansen stephen at cerebralmaelstrom.com
Sat Sep 16 14:18:32 EDT 2000


First of all, any methods (functions defined within a class definition) 
require at least one argument, 'self', which will be automatically
passed to it when you call the function.

E.g., your code should be:

class C:
	def __init__(self):
		self.color = 'green'

Secondly, "color = 'green'" as you wrote it would be local to the
function, so it would cease-to-exist as soon as the function is
finished; it would not be assigned to the class. You need to 
say 'self.attribute' to assign variables to class _instances_.

Attributes assigned in class definitions are shared with all the
instances; when you change them in an instance, you're actually
changing them in the class-parent itself.

So:

class C:
	firstcolor = 'green'
	def __init__(self):
		self.secondcolor = 'red'

'firstcolor' would be shared by all instances, and 'secondcolor'
would be local to each individual instance, with a default of 'red'.

As for class inheritance, try: "class C(A):"  to have class C 
inherit from class A.

--Stephen
In article <4mOw5.5327$ZN4.805678 at news1.cableinet.net>, "Brett Lempereur"
<a.lempereur[remove this|@|remove this]cableinet.co.uk> wrote:

> I think this is right, here's a little example i hope is correct
> 
> If you have created two instances of one class, if you change the master
> without asigning something to the child, the child will always refer to
> the master
> 
> So if you haven't actually set the color in class A or B it will always
> refer to its parent class before it does anything.  If however you were
> to do this in the class
> 
> class C:
>     def __init__():
>         color = "green"
> 
> You wouldn't have the problem of the global colour changes.  I think
> 
> Oh yeah, anybody know how to implement class inheritance in Python?
> 
>


-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----



More information about the Python-list mailing list