how to ask for class attribute?

Jonathan Hogg jonathan at onegoodidea.com
Mon Jul 22 05:16:09 EDT 2002


On 22/7/2002 9:23, in article 3D3BC0F8.4648E69A at ipm.fhg.de, "Markus von Ehr"
<markus.vonehr at ipm.fhg.de> wrote:

> my class has several attributes self.*
> In one method I have to detect if there is
> already an attribute self.start_value
> How can I detect, if the attribute already exists?

Something like this should do the trick:

>>> class Foo:
...     def hasfoo( self ):
...         if hasattr(self, 'foo'):
...             print 'yes'
...         else:
...             print 'no'
... 
>>> f = Foo()
>>> f.hasfoo()
no
>>> f.foo = 5
>>> f.hasfoo()
yes
>>> 

This will be fooled by class attributes or inherited attributes though. If
you want to determine if 'foo' is an actual instance variable then you can
use:

    if name in self.__dict__: ...

Jonathan




More information about the Python-list mailing list