简体   繁体   中英

How to find out if object has attributes?

 if groupName.group == "None":

error:

AttributeError: 'NoneType' object has no attribute 'group'

How to check if object has an attribute?

你想要getattr() ,你可以传递一个默认值,或者hasattr()

The error message is telling you that groupName itself is None .

In which case, there's little point in testing whether it has a particular attribute.

So you probably want something more like:

If groupName is not None:
    print groupName.group

Or, if groupName objects may not have a group attribute:

If groupName is not None:
    print getattr(groupName, 'group', None)

(Note: the last argument of getattr is a default value that can be anything you want).

Python follows the EAFP motto, so it is claimed to be better style just to try and handle an exception.

So try

try:
    gr = groupName.group
except AttributeError:
    complain()
else:
    if gr == "None":
        go_on()

But beware: I'm not sure if your == "None" is what you want. Maybe is None would be the thing...

It depends on what you call "to have an attribute".

.

hasattr()

If you want to verify if an expression Xa will return something or raise an error, you can use hasattr()

def f(x,y):
    return x+y
f.a = 'suming function'
print "hasattr(f,'a') : ",hasattr(f,'a'),'     f.a : ',f.a
print "hasattr(f,'sdjk') : ",hasattr(f,'sdjk'),'     f.sdjk : ',f.sdjk

produces

hasattr(f,'a') :  True      f.a :  suming function
hasattr(f,'sdjk') :  False      f.sdjk : 

Traceback (most recent call last):
  File "I:\all\aaaaa.py", line 26, in <module>
    print "hasattr(f,'sdjk') : ",hasattr(f,'sdjk'),'     f.sdjk : ',f.sdjk
AttributeError: 'function' object has no attribute 'sdjk'

.

__dict__

But it may happen that calling an attribute on an instance with a certain name returns something while there is not really this name in the namespace of the instance, that is to say no item name:object in the dictionary of this instance's attributes.

It's the case with a class attribute : a class attribute is returned when a call of its name is done on one of the instances of the class, while this name doesn't exist in the namespace of the instance. See example:

class Tomo:
    count = 0
    def __init__(self):
        Tomo.count += 1
    pass

ti = Tomo()
ta = Tomo()
tu = Tomo()
ty = Tomo()
print 'ty.count ==',ty.count,"       hasattr(ty,'count') ==",hasattr(ty,'count')
print 'ty.__dict__ ==',ty.__dict__,"   'count' in ty.__dict__ ==",'count' in ty.__dict__
print

result

ty.count == 4        hasattr(ty,'count') == True
ty.__dict__ == {}    'count' in ty.__dict__ == False    

So
hasattr(ty,'count') says "YES"
while 'count' in ty.__dict__ says "NO, ty doesn't have an attribute count " .

.

Then , asking hasattr(object,name) gives less precise answer on the state of the real objects in a program than asking name in object.__dict__ , though hasattr() gives more pertinent information concerning the treatment of data that is the practical aim of running a program.

So , I think that use of hasattr() is rather associated to the algorithm , and use of __dict__ rather associated to the comprehension of the underlying mechanisms of a running program.

.

dir()

Theoretically dir(object) gives the keys of the dictionnary __dict__ of the object.
But

dir([object]) Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. If the object does not provide __dir__() , the function tries its best to gather information from the object's __dict__ attribute, if defined, and from its type object

Hence, there is the same problem with dir() than with hasattr() : it gives more attributes than the only ones being exactly in an object and not in its parent classes.

.


.

By the way, I presume it will be OK if you do:

if hasattr(groupName,'group') and groupName.group is None:
    ..........
    .....
    ........

It is said that it's better to use is for testing None than ==

In python there's a motto: Better to Say Sorry than Ask Permission. I would suggest to find out what are your needs and eventually do something like:

try:
  # do something with groupName.group

except SomeException, e: ...
  # act some other way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM