Python: Class factory using user input as class names

后端 未结 2 1711
清酒与你
清酒与你 2021-02-03 10:41

I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasse

相关标签:
2条回答
  • 2021-02-03 11:20

    Have a look at the type() builtin function.

    knight_class = type('Knight', (Unit,), {})
    
    • First parameter: Name of new class
    • Second parameter: Tuple of parent classes
    • Third parameter: dictionary of class attributes.

    But in your case, if the subclasses don't implement a different behaviour, maybe giving the Unit class a name attribute is sufficient.

    0 讨论(0)
  • 2021-02-03 11:21

    To create a class from a name, use the class statement and assign the name. Observe:

    def meta(name):
        class cls(Unit):
            pass
    
        cls.__name__ = name
        return cls
    

    Now I suppose I should explain myself, and so on. When you create a class using the class statement, it is done dynamically-- it is equivalent of calling type().

    For example, the following two snippets do the same thing:

    class X(object): pass
    X = type("X", (object,), {})
    

    The name of a class-- the first argument to type-- is assigned to __name__, and that's basically the end of that (the only time __name__ is itself used is probably in the default __repr__() implementation). To create a class with a dynamic name, you can in fact call type like so, or you can just change the class name afterward. The class syntax exists for a reason, though-- it's convenient, and it's easy to add to and change things later. If you wanted to add methods, for example, it would be

    class X(object):
        def foo(self): print "foo"
    
    def foo(self): print "foo"
    X = type("X", (object,), {'foo':foo})
    

    and so on. So I would advise using the class statement-- if you had known you could do so from the beginning, you likely would have done so. Dealing with type and so on is a mess.

    (You should not, by the way, call type.__new__() by hand, only type())

    0 讨论(0)
提交回复
热议问题