Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - How to set class names dynamically?

I have a function that creates classes derived from it's arguments:

def factory(BaseClass) :
    class NewClass(BaseClass) : pass
    return NewClass

Now when I use it to create new classes, the classes are all named the same, and the instances look like they have the same type:

NewA = factory(ClassA)
NewB = factory(ClassB)
print type(NewA()) # <class __main__.NewClass>
print type(NewB()) # <class __main__.NewClass>

Is the proper fix to manually set the __name__ attribute?

NewA.__name__ = 'NewA'
print type(NewA()) # <class __main__.NewA>

Are there any other things I should be setting while I'm at it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, setting __name__ is the correct thing to do; you don't need to set anything else to adjust the class name.

For example:

def factory(BaseClass) :
    class NewClass(BaseClass): pass
    NewClass.__name__ = "factory_%s" % BaseClass.__name__
    return NewClass

type is the wrong thing to use here. It doesn't let you define classes with Python's normal class syntax, instead making you set up every class attribute manually. It's used to create classes by hand, e.g. if you have an array of base classes and you want to create a class using it (which you can't do with Python's class syntax). Don't use it here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...