python - Python 类方法的示例用例是什么?

标签 python class class-method

我已阅读 What are Class methods in Python for?但是该帖子中的示例很复杂。我正在为 Python 中的类方法的特定用例寻找一个清晰、简单、简单的示例。

您能否举出一个小的、具体的示例用例,其中 Python 类方法将成为该工作的正确工具?

最佳答案

用于初始化的辅助方法:

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 - Python 类方法的示例用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5738470/

相关文章:

java - 如何在java中使用类型变量创建参数化类型?

python - 速度静态方法与类方法

ruby - 在具有变量名称的模块中定义类方法

python 类方法 get_by_user 返回 None

python - 当模块名称中包含 '-' 破折号或连字符时如何导入模块?

python - 二进制补码函数输出 -1 的错误结果

php - 值未传递到查询中

python - 获取 Mechanize 中 br.forms() 的键和值

python - PySide2 加载和创建组件时发生了什么?

c++ - 对象 std::string 出错