C++ 公认的 Python 替代方案是什么?重载输入流运算符?
在 C++ 中,您可以这样做以轻松地将数据读入类中:
istream& operator >> (istream& instream, SomeClass& someclass) {
...
}
在 python 中,我能找到从控制台读取的唯一方法是“raw_input”函数,该函数不太适合此类事情。有没有一种Pythonic的方法来解决这个问题?
In C++, you can do this to easily read data into a class:
istream& operator >> (istream& instream, SomeClass& someclass) {
...
}
In python, the only way I can find to read from the console is the "raw_input" function, which isn't very adaptable to this sort of thing. Is there a pythonic way to go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您本质上是在寻找反序列化。 Python 有多种选项,具体取决于所使用的库。默认是 python pickling。还有很多其他选项,您可以这里查看< /a>.
You are essentially looking for deserialization. Python has a myriad of options for this depending on the library used. The default is python pickling. There are lots of other options you can have a look here.
不,没有广泛的 Pythonic 约定“从这个打开的输入文本文件中读取类 X 的下一个实例”。我相信这适用于大多数语言,包括 Java; C++ 是一种异常值(许多 C++ 商店禁止在其本地样式指南中使用
operator>>
)。另一个答案建议的序列化(如果您需要据称人类可读的文本文件,则序列化到 JSON 或 XML)是一种可能的方法,但不太热(没有标准化的方法将完全通用的类实例序列化为 XML 或 JSON)。No, there's no widespread Pythonic convention for "read the next instance of class X from this open input text file". I believe this applies to most languages, including e.g. Java; C++ is kind of the outlier there (and many C++ shops forbid the
operator>>
use in their local style guides). Serialization (to/from JSON or XML if you need allegedly-human readable text files), suggested by another answer, is one possible approach, but not too hot (no standardized way to serialize completely general class instances to either XML or JSON).您可以从 sys.stdin (类似文件的对象)读取,而不是使用 raw_input:
Rather than use raw_input, you can read from sys.stdin (a file-like object):