PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 24, 2022

[FIXED] How to get all objects in a module in python?

 November 24, 2022     module, python     No comments   

Issue

I need to get a list of all the objects within a module -- not a list of just their names. So, for instance, I have:

class myClass:  
    def __init__(self):  
        # here be code
        pass

class thing1(myClass):  
    def __init__(self):  
        self.x = 1

class thing2(myClass):  
    def __init__(self):
        self.x = 2

and so on.

What I want is something that will give me a list of the objects in myClass (thing1, thing2) from which I can call methods / get attributes. I'm trying to do something like this:

for myThing in dir(myClass):  
    print myThing.x

But the dir function only gives a list of the names of the classes, and I can't get the attribute from that.

How can I do this?


Solution

If you have the name of an attribute in a string, you should use getattr to fetch it out.

Given a module X, you can get a list of all it's attributes and (for example) their types with something like this.

for i in dir(X):
   print (i,"  ",type(getattr(X,i)))


Answered By - Noufal Ibrahim
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing