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
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.
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.
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.
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.
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
import types
print isinstance(getattr(your_object, "your_attribute"), types.MethodType)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With