Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a class attribute is an instance method

In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.

hasattr returns true regardless of whether the attribute is an instance method or not.

Any suggestions?


For example:

class Test(object):
    testdata = 123

    def testmethod(self):
        pass

test = Test()
print ismethod(test, 'testdata') # Should return false
print ismethod(test, 'testmethod') # Should return true
like image 246
Richard Dorman Avatar asked Jul 07 '09 09:07

Richard Dorman


People also ask

What is the difference between class attributes and instance?

Differences Between Class and Instance Attributes The difference is that class attributes are shared by all instances. When you change the value of a class attribute, it will affect all instances that share the same exact value. The attribute of an instance on the other hand is unique to that instance.

Can a class attribute be used without an instance of that class?

while you can access class attributes using an instance it's not safe to do so. In python, the instance of a class is referred to by the keyword self. Using this keyword you can access not only all instance attributes but also the class attributes.

What is the difference between an attribute and an instance?

Classes contain characteristics called Attributes. We make a distinction between instance attributes and class attributes. Instance Attributes are unique to each object, (an instance is another name for an object). Here, any Dog object we create will be able to store its name and age.

Can a class contain instance attributes and instance methods?

Instance attributes are for data specific for each instance and class attributes supposed to be used by all instances of the class. "Instance methods" is a specific class attributes which accept instance of class as first attribute and suppose to manipulate with that instance.


2 Answers

You can use the inspect module:

class A(object):
    def method_name(self):
        pass


import inspect

print inspect.ismethod(getattr(A, 'method_name')) # prints True
a = A()
print inspect.ismethod(getattr(a, 'method_name')) # prints True
like image 73
Steef Avatar answered Oct 09 '22 15:10

Steef


import types

print isinstance(getattr(your_object, "your_attribute"), types.MethodType)
like image 42
mthurlin Avatar answered Oct 09 '22 16:10

mthurlin