-2
class dheepak():
    age = 23
    name = "dheepak sasi"

ankit = getattr(dheepak, "hostname", ' ')
if ankit == None:
    print "Shanaya"
else:
    print "byee"
mani = dheepak.age

print ankit

if hostname doesnot exist than it should print Shanaya if hostname present than print byee. And hostname value is coming from another program sometimes it comes sometimes not

Ankit Singh
  • 193
  • 1
  • 4
  • 13

2 Answers2

4

You are supplying a space as the value for ankit if there is no such attribute, but checking for None. Be consistent:

ankit = getattr(dheepak, "hostname", None)
if ankit is None:
   ...

or

ankit = getattr(dheepak, "hostname", ' ')
if ankit == ' ':
   ...

Better yet, don't try to define a sentinel value at all; just catch the exception raised by getattr when the attribute doesn't exist.

try:
    ankit = getattr(dheepak, "hostname")
except AttributeError:
    print "Shanaya"
else:
    print "byee"
chepner
  • 497,756
  • 71
  • 530
  • 681
0

How about this:

class dheepak():
    age = 23
    name = "dheepak sasi"

ankit = getattr(dheepak, "hostname", '')
if not ankit:
    print "Shanaya"
else:
    print "byee"
mani = dheepak.age

print ankit
zipa
  • 27,316
  • 6
  • 40
  • 58