Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Introspecting arguments from the constructor function __init__ in Python

What is a way to extract arguments from __init__ without creating new instance. The code example:

class Super:
    def __init__(self, name):
        self.name = name

I am looking something like Super.__dict__.keys()type solution. Just to retrieve name argument information without adding any values. Is there such an option to do that?

like image 478
Vy.Iv Avatar asked Apr 25 '16 19:04

Vy.Iv


People also ask

What is __ init __ constructor in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

How many arguments can this method take __ Init__?

Here, the __init__() function will take two argument values at the time of the object creation that will be used to initialize two class variables, and another method of the class will be called to print the values of the class variables.

What is __ init __ In Python class?

"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.

What is the correct syntax for defining an __ init __ method in Python?

We can declare a __init__ method inside a class in Python using the following syntax: class class_name(): def __init__(self): # Required initialisation for data members # Class methods … …


1 Answers

Update for Python 3.3+ (as pointed out by beeb in the comments)

You can use inspect.signature introduced in Python 3.3:

class Super:
    def __init__(self, name, kwarg='default'):
        print('instantiated')
        self.name = name

>>> import inspect
>>> inspect.signature(Super.__init__)
<Signature (self, name, kwarg='default')>

Original answer below

You can use inspect

>>> import inspect
>>> inspect.getargspec(Super.__init__)
ArgSpec(args=['self', 'name'], varargs=None, keywords=None, defaults=None)
>>> 

Edit: inspect.getargspec doesn't actually create an instance of Super, see below:

import inspect

class Super:
    def __init__(self, name):
        print 'instantiated'
        self.name = name

print inspect.getargspec(Super.__init__)

This outputs:

### Run test.a ###
ArgSpec(args=['self', 'name'], varargs=None, keywords=None, defaults=None)
>>> 

Note that instantiated never got printed.

like image 57
Bahrom Avatar answered Oct 17 '22 07:10

Bahrom