getting attributes and methods of class without creating object

shuvro shuvro05 at gmail.com
Tue May 18 02:11:29 EDT 2010


On May 18, 11:50 am, Patrick Maupin <pmau... at gmail.com> wrote:
> On May 17, 10:52 pm, shuvro <shuvr... at gmail.com> wrote:
>
>
>
> > Suppose I have a class like this -
>
> > class myClass(object):
>
> >     def __init__(self):
> >         self.a = 10
> >         self.b = 20
>
> >     def my_method(self,var = 20):
> >         self.local_var = var
>
> > I want to know about its method(__init__ and my_method) and
> > variables(a,b, local_var) without creating the object of it. I tried
> > getmembers function of inspect module. But it can do this with an
> > object of myClass as argument. Like
>
> > import inspect
> > var = myClass()
> > inspect.getmembers(var)
>
> > I have to know about this without creating the object of myClass.
> > Can anyone help me please?
>
> Well, you can do the same thing with myClass itself:
>
> inspect.getmembers(myClass)
>
> But that won't show you a,b, or local_var, because those don't belong
> to the class.  They only belong to class instances, and maybe even not
> all class instances.  (For example, if my_method is not called, then
> the instance won't have local_var defined.)
>
> Python is a very dynamic language, and class instances (and even the
> classes themselves!) can be modified at any time during execution.
> You don't even have to be executing inside a class's function to add
> stuff to it:
>
> class foo:
>     pass
>
> bar = foo()
> bar.a = 3
>
> So to "know" about the attributes of an instance of a class without
> actually creating that instance is very difficult.  You didn't specify
> why you want to do this, but often the reason is to try to catch
> potential errors without actually running code.  This is typically
> called "linting", and there are a few Python packages designed to do
> this, such as pylint and pychecker.  Probably others, but I don't know
> anything about them, because I find that in most cases, the best way
> to test or to reason about Python code is to actually run it.
>
> Regards,
> Pat

Thanks Pat for your informative reply.
Actually what I am trying to do is to write an external exporter for
the data types an open source software(Blender). So, I have to collect
the properties of the classes.
Here, I have no chance to edit the class and add inspect codes there,
neither I can create objects of the
existing classes (that will do some additional things which I not
want).
Is it not possible with the existing python facilities (without adding
external libraries) ?


Shuvro



More information about the Python-list mailing list