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

后端 未结 6 1491
傲寒
傲寒 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

    I don't know, something like named constructor methods?

    class UniqueIdentifier(object):
    
        value = 0
    
        def __init__(self, name):
            self.name = name
    
        @classmethod
        def produce(cls):
            instance = cls(cls.value)
            cls.value += 1
            return instance
    
    class FunkyUniqueIdentifier(UniqueIdentifier):
    
        @classmethod
        def produce(cls):
            instance = super(FunkyUniqueIdentifier, cls).produce()
            instance.name = "Funky %s" % instance.name
            return instance
    

    Usage:

    >>> x = UniqueIdentifier.produce()
    >>> y = FunkyUniqueIdentifier.produce()
    >>> x.name
    0
    >>> y.name
    Funky 1
    

提交回复
热议问题