Methods of setting class attributes

hnowak hnowak at
Wed Jul 25 07:02:40 EDT 2001

>===== Original Message From Piotr Legiecki <piotrlg at> 

>I'm C++ user and new to Python. I don't know what is the proper method
>of setting attribute value in a class. I thought that this is ok:
>class a:
>  atr1=0
>  atrb=1

Do you mean class attributes or instance attributes? It's not the same in 

Assuming you just want the default behavior to set attributes in a class and 
get going, this is a common idiom:

class Foo:
    def __init__(self, x):
        self.x = x
        self.y = "blah"

This creates attributes x and y when Foo is instantiated:

foo = Foo(3)
print foo.x, foo.y
# prints 3 and blah

Note that this is different from a class attribute; those are often used to 
share values between instances:

>>> class Counter:
	count = 0
	def __init__(self):
		Counter.count += 1
	def __del__(self):
		Counter.count -= 1
	def report(self):
		print "Ah, already", Counter.count, "instances created!"

This class keeps track of the number of instances. It does so by assigning to 
Counter.count, which resides at the class level (as opposed to the instance 

>>> c1 = Counter()
Ah, already 1 instances created!
>>> c2 = Counter()
>>> c3 = Counter()
Ah, already 3 instances created!
Ah, already 3 instances created!
>>> Counter.count
>>> c3.count  # Counter.count can be accessed through the instance
>>> dir(c3) # attributes of c3 (none)
>>> dir(Counter) # attributes of class Counter
['__del__', '__doc__', '__init__', '__module__', 'count', 'report']
>>> del c2 # remove an instance
Ah, already 2 instances created!

Python is much more dynamic than C++ and attributes of a class or instance can 
be set or deleted at will.

>__setattr__(s, name, val) called when setting an attr
>                                  (inside, don't use " = value"
>                                   use "self.__dict__[name] = val")

I think it's best to forget __setattr__ for now; it's mainly used to fake 
attributes and control values assigned to an attribute.


--Hans Nowak

More information about the Python-list mailing list