[Level 2] How to verify instance has attribute (variables in global/local) or not.

$ cat ./test1.py
#!/bin/env python
class myClass:
    def __init__(self):
        self.attr1 = 'a'
        self.attr2 = 'b'
    def checkAttr(self, sAttr):
        return hasattr(self, sAttr)

mc = myClass()
print hasattr(mc, 'attr1')
print hasattr(mc, 'attr2')
print hasattr(mc, 'attr3')
print mc.checkAttr('attr1')
print mc.checkAttr('attr2')
print mc.checkAttr('attr3')
$ ./test1.py
True
True
False
True
True
False
$ cat ./test2.py
#!/bin/env python
## cannot extract test locals() in another method! ##
def testExistInGlobal():
#    print globals()
#    print locals()
    print 'a in globals(): %s' % ('Ture' if 'a' in globals() else 'False')
    print 'b in globals(): %s' % ('Ture' if 'b' in globals() else 'False')
#    print 'a in locals(): %s' % ('Ture' if 'a' in locals() else 'False')
#    print 'b in locals(): %s' % ('Ture' if 'b' in locals() else 'False')

def inFunc1():
    a=2
    print a
    print b
    testExistInGlobal()
    print 'a in locals(): %s' % ('Ture' if 'a' in locals() else 'False')
    print 'b in locals(): %s' % ('Ture' if 'b' in locals() else 'False')

def inFunc2(b):
    b=3
    print a
    print b
    testExistInGlobal()

print '-' * 20
print 'before assign a=1, b=2'
testExistInGlobal()
print 'a in locals(): %s' % ('Ture' if 'a' in locals() else 'False')
print 'b in locals(): %s' % ('Ture' if 'b' in locals() else 'False')

a=1
b=2

print '-' * 20
print 'after assign a=1, b=2'
testExistInGlobal()
print 'a in locals(): %s' % ('Ture' if 'a' in locals() else 'False')
print 'b in locals(): %s' % ('Ture' if 'b' in locals() else 'False')

print '-' * 20
print 'test in method1, a=2'
inFunc1()

print '-' * 20
print 'test in method2, b=3'
inFunc2(b)

print '-' * 20
print 'back to main'
testExistInGlobal()
print 'a in locals(): %s' % ('Ture' if 'a' in locals() else 'False')
print 'b in locals(): %s' % ('Ture' if 'b' in locals() else 'False')
print a
print b
$ ./test2.py 
--------------------
before assign a=1, b=2
a in globals(): False
b in globals(): False
a in locals(): False
b in locals(): False
--------------------
after assign a=1, b=2
a in globals(): Ture
b in globals(): Ture
a in locals(): Ture
b in locals(): Ture
--------------------
test in method1, a=2
2
2
a in globals(): Ture
b in globals(): Ture
a in locals(): Ture
b in locals(): False
--------------------
test in method2, b=3
1
3
a in globals(): Ture
b in globals(): Ture
a in locals(): False
b in locals(): Ture
--------------------
back to main
a in globals(): Ture
b in globals(): Ture
a in locals(): Ture
b in locals(): Ture
1
2
Wish this helps. regards, Stanley Huang

Comments

Popular posts from this blog

[Level 1] Reversion of git

[Level 2] iif in Python