Dynamic class definition in Python

A smarter factory method could even guess the best class to use, by looking at the structure of the data argument.def chart_factory(title, data, style): if style == "bar": return BarChart(title, data) if style == "scatter": return Scatter(title, data) else: raise Exception("Unrecognized chart style.")chart = chart_factory("New Chart", data, "bar")chart.plot()Factory methods are great when you know in advance which classes you want to return, and the conditions under which they are returned.But what if you don’t even know this in advance?Dynamic definitionsPython lets you define classes dynamically, and instantiate objects with them as required.Why might you want to do this..The short answer is yet more abstraction.Admittedly, needing to write code at this level of abstraction is generally a rare occurrence..As always in programming, you should consider if there is an easier solution.However, there may be times when it genuinely proves useful to define classes dynamically?.We’ll cover a possible use-case below.You may be familiar with Python’s type() function..With one argument, it simply returns the “type” of the object of the argument.type(1) # <type 'int'>type('hello') # <type 'str'>type(True) # <type 'bool'>But, with three arguments, type() returns a whole new type object..This is equivalent to defining a new class.NewClass = type('NewClass', (object,), {})The first argument is a string that gives the new class a nameThe next is a tuple, which contains any base classes the new class should inherit fromThe final argument is a dictionary of attributes specific to this classWhen might you need to use something as abstract as this..Consider the following example.Flask Table is a Python library that generates syntax for HTML tables..It can be installed via the pip package manager.You can use Flask Table to define classes for each table you want to generate..You define a class that inherits from a base Table class!.Its attributes are column objects, which are instances of the Col class.from flask_table import Table, Colclass MonthlyDownloads(Table): month = Col('Month') downloads = Col('Downloads')data = [{'month':'Jun', 'downloads':700}, {'month':'Jul', 'downloads':900}, {'month':'Aug', 'downloads':1600}, {'month':'Sep', 'downloads':1900}, {'month':'Oct', 'downloads':2200}]table = MonthlyDownloads(data)print(table.__html__())You then create an instance of the class, passing in the data you want to display..The __html__() method generates the required HTML.Now, say you’re developing a tool that uses Flask Table to generate HTML tables based on a user-provided config file..You don’t know in advance how many columns the user wants to define — it could be one, it could be a hundred.. More details

Leave a Reply