Methods of setting class attributes

hnowak hnowak at cuci.nl
Wed Jul 25 13:02:40 CEST 2001


>===== Original Message From Piotr Legiecki <piotrlg at sci.pam.szczecin.pl> 
=====

>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 
Python.

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 
level).

>>> c1 = Counter()
>>> c1.report()
Ah, already 1 instances created!
>>> c2 = Counter()
>>> c3 = Counter()
>>> c3.report()
Ah, already 3 instances created!
>>> c1.report()
Ah, already 3 instances created!
>>> Counter.count
3
>>> c3.count  # Counter.count can be accessed through the instance
3
>>> dir(c3) # attributes of c3 (none)
[]
>>> dir(Counter) # attributes of class Counter
['__del__', '__doc__', '__init__', '__module__', 'count', 'report']
>>> del c2 # remove an instance
>>> c1.report()
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 "self.name = 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.

HTH,

--Hans Nowak





More information about the Python-list mailing list