当我发现一些东西时,我正在尝试在 python 中使用 dunders:假设我创建了一个类:
class MyInt:
def __init__(self, val):
self.val = val
def __add__(self, other):
return self.val + other
a = MyInt(3)
Run Code Online (Sandbox Code Playgroud)
该__add__工程时,这是运行完美的罚款:
>>> print(a + 4)
7
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此命令时:
>>> print(4 + a)
TypeError: unsupported operand type(s) for +: 'int' and 'MyInt'
Run Code Online (Sandbox Code Playgroud)
我知道该int课程不支持添加 with MyInt,但是有什么解决方法吗?
最近开始自学C++,上网找了些挑战。我发现了一个挑战,需要我将字符串的每个字符都加倍。(例如:“abcd”->“aabbccdd”)
我做了一个简单的程序:
#include <iostream>
using namespace std;
string doubleChar(string str) {
string result = "";
for (int i=0; i<str.length(); i++){
result += str[i] + str[i];
}
return result;
}
int main()
{
string stuff = "Example Text";
cout << doubleChar(stuff);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我期望"EExxaammppllee TTeexxtt",或者至少是如果代码错误我可以推断出错误的结果。但是,当我运行下面的代码时,得到了一个相当奇怪的结果:"è??????@¿???"
我对 C++ 真的很陌生,对它一无所知,所以我不知道在线谷歌什么。我尝试搜索“在 C++ 中添加字符串时的奇怪字符”或类似的东西,但找不到任何东西。我怀疑它可能与str[i] + str[i]
提前致谢