Python类方法的一个示例用例是什么? [英] What's an example use case for a Python classmethod?

查看:138
本文介绍了Python类方法的一个示例用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 Python中的类方法是什么?但是在那篇文章中的例子很复杂。我正在寻找一个清楚,简单,基本的例子的Python中的类方法的特定用例。

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 for classmethods in Python.

您可以命名一个小型,具体的示例用例,其中Python类方法是正确的工作工具吗?

Can you name a small, specific example use case where a Python classmethod would be the right tool for the job?

推荐答案

初始化的帮助方法:

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):
       ...

这篇关于Python类方法的一个示例用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆