Hasattr in class names

The hasattr documentation says that it accepts the name of the object and attribute and lets you know if this attribute exists on this object.

I found that it also works on class names (i.e. is not an instance of an object).

Sort of:

class A:
    def Attr1(self):
        pass

> hasattr(A, 'Attr1')
True
> 

I would like to use this to make some test code easier to write, but I don't want to be bitten later if this is a side effect of the implementation, and not really.

Please do not ask to see the test code to find out if I can do something else, since this is not really a question.

Is there any official python position? I assume that the object in question in the documentation speaks of an instance object.

googling ( StackOverflow), , , .

+4
3

, class , . , hasattr , . , - :

def hasattr(obj, attribute):
    try:
        getattr(obj, attribute)
    except:
        return False
    return True

. , python-dev hasattr . , hasattr , .


, python type.

>>> class Foo(object):
...   pass
... 
>>> type(Foo)
<type 'type'>

- 1.

1type , ...

+5

" Python", . ,

instance_of_SomeClass.some_method(parameters, ...)

SomeClass.some_method(instance_of_SomeClass, parameters, ...)

. hasattr.

+2

Source: https://habr.com/ru/post/1584946/


All Articles