鱼C论坛

 找回密码
 立即注册
查看: 490|回复: 8

[技术交流] python版C++(闲的)

[复制链接]
发表于 2024-7-16 23:32:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. class CoutClass:
  2.     def __lshift__(self, other):
  3.         print(other, end="")
  4.         return self
  5. cout = CoutClass()
  6. endl = "\n"


  7. cout << "1 + 1 = " << 1 + 1 << endl;
  8. cout << "emmmmmm..." << endl;
复制代码


可惜,cin无法实现

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-7-16 23:34:07 | 显示全部楼层
哈,Python 版的 C++,让我们来玩一下吧!这段代码实现了一个简单的 `cout` 类,让我们可以像 C++ 中那样使用 `<<` 运算符来输出内容。

  1. class CoutClass:
  2.     def __lshift__(self, other):
  3.         print(other, end="")
  4.         return self

  5. cout = CoutClass()
  6. endl = "\n"

  7. cout << "Hello, World!" << endl
  8. cout << "Python meets C++ magic!" << endl
复制代码


在这里,我们创建了一个 `CoutClass` 类,重载了 `__lshift__` 方法,使得对象 `cout` 可以接受 `<<` 运算符,用于打印内容。`endl` 变量代表换行符,在需要换行时使用。

输出结果会像这样:
  1. Hello, World!
  2. Python meets C++ magic!
复制代码


这种写法虽然有些不同寻常,但是可以模仿 C++ 中流式输出的风格,尽管 Python 本身有更直接的输出方式。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-7-17 07:32:03 | 显示全部楼层
cin确实无法完美的实现,但还是模仿了一下
  1. a = ['']
  2. b = ['']

  3. class Cin:
  4.     def __rshift__(self, other):
  5.         other[0] = input()
  6.         return self

  7. cin = Cin()
  8. cin >> a >> b;
  9. print(a[0], b[0])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-17 10:32:15 | 显示全部楼层
liuhongrun2022 发表于 2024-7-17 07:32
cin确实无法完美的实现,但还是模仿了一下

6
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-17 13:38:43 | 显示全部楼层
liuhongrun2022 发表于 2024-7-17 07:32
cin确实无法完美的实现,但还是模仿了一下

实现不了空格切断
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-7-17 13:57:48 | 显示全部楼层

我去研究一下
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-17 20:04:37 | 显示全部楼层
  1. class CppClass:
  2.     def __lshift__(self, other):
  3.         print(other, end="")
  4.         return self
  5.     def __rshift__(self, other):
  6.         datas = input().split()
  7.         for i, dtype in enumerate(other.datas):
  8.             other.datas[i] = dtype(datas[i])
  9. class Input:
  10.     def __init__(self, *dtypes):
  11.         self.datas = list(dtypes)
  12.     def __rshift__(self, other):
  13.         return Input(self.data + other.data)
  14. cout = cin = CppClass()
  15. endl = "\n"

  16. a = Input(int, str)
  17. cin >> a;
  18. cout << a.datas;
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-8-7 21:07:33 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-8-8 12:51:34 | 显示全部楼层
一点沙 发表于 2024-8-7 21:07
芜湖回归了(指我)

我草我前几天刚想到你
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-21 05:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表