static variables
Steven D'Aprano
steve at pearwood.info
Mon Nov 30 20:01:21 EST 2015
On Tue, 1 Dec 2015 07:32 am, BartC wrote:
> On 30/11/2015 17:15, Ulli Horlacher wrote:
>> def main():
>> a(1)
>> a(2)
>> a()
>> print(a.x)
>> if 'a.x' in globals(): print('global variable')
>> if 'a.x' in locals(): print('local variable')
>
> Try this:
>
> if 'x' in a.__dict__: print('attribute of a')
That will work in this specific case, but it isn't guaranteed to always
work. Not all objects have a __dict__, even if they can hold attributes,
and not all attributes are stored in a __dict__.
A better and more general test is:
if hasattr(a, 'x'): print('attribute of a')
--
Steven
More information about the Python-list
mailing list