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?
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.
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.
"__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.
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 … …
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With