Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the least-bad way to create Python classes at runtime?

Tags:

python

class

I am working with an ORM that accepts classes as input and I need to be able to feed it some dynamically generated classes. Currently, I am doing something like this contrived example:

def make_cls(_param):
   def Cls(object):
       param = _param
   return Cls

A, B = map(make_cls, ['A', 'B'])

print A().foo
print B().foo

While this works fine, it feels off by a bit: for example, both classes print as <class '__main__.Cls'> on the repl. While the name issue is not a big deal (I think I could work around it by setting __name__), I wonder if there are other things I am not aware of. So my question is: is there a better way to create classes dynamically or is my example mostly fine already?

like image 560
hugomg Avatar asked Feb 10 '12 20:02

hugomg


People also ask

Do classes slow down python?

No. In general you will not notice any difference in performance based on using classes or not. The different code structures implied may mean that one is faster than the other, but it's impossible to say which. Always write code to be read, then if, and only if, it's not fast enough make it faster.

When should you create a class in python?

As a rule of thumb, when you have a set of data with a specific structure and you want to perform specific methods on it, use a class. That is only valid, however, if you use multiple data structures in your code. If your whole code won't ever deal with more than one structure.

Why are classes useful in Python?

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.

What is the difference between class and DEF in Python?

class is used to define a class (a template from which you can instantiate objects). def is used to define a function or a method. A method is like a function that belongs to a class.


1 Answers

What is class? It is just an instance of type. For example:

>>> A = type('A', (object,), {'s': 'i am a member', 'double_s': lambda self: self.s * 2})
>>> a = A()
>>> a
<__main__.A object at 0x01229F50>
>>> a.s
'i am a member'
>>> a.double_s()
'i am a memberi am a member'

From the doc:

type(name, bases, dict)

Return a new type object. This is essentially a dynamic form of the class statement.

like image 63
Roman Bodnarchuk Avatar answered Oct 13 '22 12:10

Roman Bodnarchuk