[Tutor] asigning class variables
Steven D'Aprano
steve at pearwood.info
Sun Feb 14 07:53:07 CET 2010
On Sun, 14 Feb 2010 12:08:40 pm the kids wrote:
> Hi, my name is John Paul.
>
> I was trying to define a class but I can't make it asign particular
> objects particular variables at their creation. Please help.
>
> John Paul
I don't quite follow what you mean, it is best if you can show example
code and describe what you expect and what you get instead.
But first a brief note on terminology. In some other languages, people
talk about "class variables" being variables that are part of the
class. To me, that's inconsistent with everything else:
an int variable holds an int;
a string variable holds a string;
a list variable holds a list;
so a class variable should hold a class.
(You might argue, why would you ever need a variable that was a class?
As an experience Python programmer, I can tell you such a thing is
very, very useful, and far more common than you might think.)
Anyway, in Python circles, it is much more common to describe class
variables as attributes. Other languages use the term "members", and
people who used Apple's Hypercard will remember the term "properties"
(but properties in Python are slightly different).
Python has two sorts of attributes (class variables, a.k.a. members):
* Attributes which are attached to the class itself, and therefore
shared by all the instances. These are known as "class attributes".
* Much more common is the ordinary sort of attribute that is attached to
instances; these are usually known as "instance attributes", or more
often, just plain old attributes.
You create a class attribute (shared by all instances) by assigning to a
name inside the class definition:
class K:
shared = []
This is now shared between all instances.
You create an instance attribute (not shared) by assigning it inside a
method, using the usual attribute syntax. The usual place to do this is
inside the __init__ method. (Note that __init__ has TWO underscores at
both the beginning and end.)
class K:
shared = []
def __init__(self):
self.attribute = []
And in use:
>>> a = K()
>>> b = K()
>>> a.shared.append(23)
>>> b.shared
[23]
>>> a.attribute.append(23)
>>> a.attribute
[23]
>>> b.attribute
[]
Using class attributes is sometimes tricky, because Python makes it
really easy to accidentally hide a class attribute with an instance
attribute with the same name, but fortunately having shared data like
this is quite rare, so it's unusual to be a problem.
Hope this helps,
--
Steven D'Aprano
More information about the Tutor
mailing list