1Mangomaster1
1Mangomaster1

Reputation: 388

Getting variables within the __init__ def in python in some class

I have a class with certain inside variables in it, let's take a simple example

    class Example:
        def __init__(self):
            self.variable = "something"
            self.anotherVariable = "somethingElse"

Now the signature in "inspect" only provides me with what's in the brackets, which in this case only the self, but can I somehow get a list of variable names within the class, so if I run that code it will result in:

Output: (self.variable, self.anotherVariable)

I appreciate all the help :)

Upvotes: 2

Views: 1370

Answers (3)

Prashant Kumar
Prashant Kumar

Reputation: 2092

There are a few ways to do this I prefer __dict__.

This is built into every class you make unless you override it. Since we’re dealing with a Python dictionary, we can just call its keys method.

Here is an example.

class Example:
    def __init__(self):
        self.variable = "something"
        self.anotherVariable = "somethingElse"

obj = Example()

variables = obj.__dict__.keys()

Output --> ['varTwo', 'varThree', 'varOne']

Hope this helps. There are also few other methods you can check out here :

http://www.blog.pythonlibrary.org/2013/01/11/how-to-get-a-list-of-class-attributes/

Upvotes: 1

Faizan Naseer
Faizan Naseer

Reputation: 627

Another way is like this; invoking dir on object itself:

class Example:
    def __init__(self):
        self.variable = 1
        self.anotherVariable = 2

obj = Example()
print([attrib for attrib in dir(obj) if not attrib.startswith("_")])

O/P

['variable', 'anotherVariable']

Upvotes: 2

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

I don't think you need inspect:

class Example:
        def __init__(self):
            self.variable = "something"
            self.anotherVariable = "somethingElse"
print(Example.__init__.__code__.co_names)

Output:

('variable', 'anotherVariable')

Upvotes: 5

Related Questions