Python Dynamic Class Creation: Flexible Method Inclusion
Creating Classes with Methods from a Template:
Write a Python function “create_class_with_methods” that takes a class name, a dictionary of attributes, and a dictionary of methods, and returns a dynamically created class with those attributes and methods.
Sample Solution:
Python Code :
Output:
Hello, I am a Human and I am 25 years old.
Explanation:
- Function Definition:
- "create_class_with_methods" takes 'name' (the name of the class), 'attrs' (a dictionary of attributes), and 'methods' (a dictionary of methods).
- Combine Attributes and Methods:
- 'attrs.update(methods)' combines the attributes and methods into a single dictionary.
- Create Class:
- The 'type' function is used to create a new class with the given 'name', inheriting from 'object', and using the combined dictionary of attributes and methods.
- Attributes Definition:
- attributes is a dictionary containing:
- species: An attribute with the value 'Human'.
- age: An attribute with the value 25.
- Methods Definition:
- methods is a dictionary containing:
- greet: A method that returns a greeting string using the 'species' and 'age' attributes.
- Create Dynamic Class:
- DynamicClass is created dynamically by calling "create_class_with_methods" with the class name, attributes, and methods.
- Testing:
- An instance of 'DynamicClass' is created.
- The "greet" method of the instance is called, returning "Hello, I am a Human and I am 25 years old."
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Python Dynamic Method Addition: Expand Class Behavior.
Next: Python Dynamic Class Inheritance: Expand with Subclass.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.