python - getattr on class objects -


class a:     def foo(self):         print "foo()"  getattr(a, foo) # true a.foo() # error  getattr(a(), foo) # true a().foo() # prints "foo()" 

that being said, here problem:

i wish store test case meta information attributes of test case class objects themselves, not on instances of them.
have list of attribute names extract, if there instance method of same name, getattr(class_obj, attr) return true, getattr(class_obj, attr)() raises error.

is there way tell getattr not include attributes of instantiated class , of class object itself?

edit: tried accessing class_obj.__dict__ directly (which understand bad practice), not include attributes __name__

edit: rephrase of question. there way differentiate between methods of class obj , methods of instance of class?

is enough?

import types class test(object):     @staticmethod     def foo():         print 'foo'      def bar(self):         print 'bar' 

in combination with:

>>>(isinstance(getattr(test, 'foo'), types.functiontype),     isinstance(getattr(test, 'bar'), types.functiontype)) true, false 

you can use inspect module:

>>> inspect.isfunction(test.foo) true >>> inspect.isfunction(test.bar) false 

with little additional work can distinguish class methods instance methods , static methods:

import inspect  def get_type(cls, attr):     try:         return [a.kind in inspect.classify_class_attrs(cls) if a.name == attr][0]     except indexerror:         return none  class test(object):     @classmethod     def foo(cls):         print 'foo'      def bar(self):         print 'bar'      @staticmethod     def baz():         print 'baz' 

you can use as:

>>> get_type(test, 'foo') 'class method' >>> get_type(test, 'bar') 'method' >>> get_type(test, 'baz') 'static method' >>> get_type(test, 'nonexistant') none 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -