What's an example use case for a Python classmethod?

后端 未结 6 1469
傲寒
傲寒 2020-12-04 07:31

I\'ve read What are Class methods in Python for? but the examples in that post are complex. I am looking for a clear, simple, bare-bones example of a particular use case fo

6条回答
  •  既然无缘
    2020-12-04 08:12

    Well __new__ is a pretty important classmethod. It's where instances usually come from

    so dict() calls dict.__new__ of course, but there is another handy way to make dicts sometimes which is the classmethod dict.fromkeys()

    eg.

    >>> dict.fromkeys("12345")
    {'1': None, '3': None, '2': None, '5': None, '4': None}
    

提交回复
热议问题