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

后端 未结 6 1464
傲寒
傲寒 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 07:59

    Helper methods for initialization:

    class MyStream(object):
    
        @classmethod
        def from_file(cls, filepath, ignore_comments=False):    
            with open(filepath, 'r') as fileobj:
                for obj in cls(fileobj, ignore_comments):
                    yield obj
    
        @classmethod
        def from_socket(cls, socket, ignore_comments=False):
            raise NotImplemented # Placeholder until implemented
    
        def __init__(self, iterable, ignore_comments=False):
           ...
    

提交回复
热议问题