简体   繁体   中英

Can you use string formatting for classes in Python?

I need to name classes certain things, for example:

for a in range(10):
    class Class#"%s"(object): % (num)
         '''Class Content'''
    num += 1

My question, is this possible, and if not, what is an alternative.

You can do it using metaclasses (stuff that is used to create classes). Example:

>>> type('ClassName', (), {})
<class '__main__.ClassName'>

Second argument is a tuple of base classes, third argument is a dictionary containing attribute name -> attribute value pairs:

>>> cls = type('ClassName', (object,), {'varname': 'var'})
>>> cls.varname
'var'

From the documentation on type function :

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute.


Also read this awesome answer for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM