2017-05-08 244 views
-3
class dheepak(): 
    age = 23 
    name = "dheepak sasi" 

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

print ankit 

如果主機名不存在,它應該打印Shanaya如果主機名存在比打印byee。和主機名值從另外一個程序來有時說到有時不如何檢查變量是否爲空?

+1

或者http://stackoverflow.com/questions/9926446/how-to-check-whether-a-strvariable-is-empty-or-not –

回答

0

如何:

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

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

print ankit 
2

您提供一個空間爲ankit的值,如果沒有這樣的屬性,但檢查None。是一致的:

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

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

更重要的是,不要試圖在所有定義的標記值;只要在該屬性不存在時捕獲由getattr引發的異常。

try: 
    ankit = getattr(dheepak, "hostname") 
except AttributeError: 
    print "Shanaya" 
else: 
    print "byee" 
+0

因爲他們並不需要的屬性值,' hasattr'可能更合適。 –

+0

我還沒有對Python 3做過多的討論,所以我仍然避免'hasattr'。 https://hynek.me/articles/hasattr/ – chepner

相關問題