Suppose I have a file with a bunch methods as bunch_methods.py:
def one(x):
return int(x)
def two(y)
return str(y)
Is there a way to take th
You can also solve this problem using the type meta-class. The format for using type to generate a class is as follows:
type(name of the class,
tuple of the parent class (for inheritance, can be empty),
dictionary containing attributes names and values)
First, we need to rework your functions to take a class as the first attribute.
def one(cls, x):
return int(x)
def two(cls, y):
return str(y)
Save this as bunch_method.py, and now we can construct our class as follows.
>>> import bunch_methods as bm
>>> Bunch_Class = type('Bunch_Class', (), bm.__dict__)
>>> bunch_object = Bunch_Class()
>>> bunch_object.__class__
>>> bunch_object.one(1)
1
>>> bunch_object.two(1)
'1'
See the following post for a excellent (and long) guide on meta-classes. What is a metaclass in Python?