小编sar*_*had的帖子

这是一个错误吗?变量是对此示例中相同字符串的相同引用(Python)

这适用于Python 2.6.

我无法弄清楚为什么a和b是相同的:

>>> a = "some_string"
>>> b = "some_string"
>>> a is b
True
Run Code Online (Sandbox Code Playgroud)

但是如果字符串中有空格,则它们不是:

>>> a = "some string"
>>> b = "some string"
>>> a is b
False
Run Code Online (Sandbox Code Playgroud)

如果这是正常行为,有人可以解释发生了什么.

编辑:免责声明!这不用于检查相等性.我其实想向其他人解释"是"只是为了检查身份,而不是平等.从文档中我了解到以这种方式创建的引用将是不同的,每次都会创建一个新的字符串.当我无法证明自己的观点时,我给出的第一个例子就把我扔了!

编辑: 我知道这不是一个错误,实习对我来说是一个新概念. 似乎是一个很好的解释.

python string reference

8
推荐指数
1
解决办法
246
查看次数

如何用非ascii"bytes"创建一个Python字符串

我需要创建一个由非ascii字节组成的Python字符串,用作C模块中的命令缓冲区.如果我手工编写字符串,我可以这样做:

mybuffer = "\x00\x00\x10"
Run Code Online (Sandbox Code Playgroud)

但是如果我有一组整数将成为字符串中的字节,我无法弄清楚如何动态创建字符串.将整数与字符串连接是TypeError.

所以,如果我有一个整数列表,我们可以说:

myintegers = [1, 2, 3, 10]
Run Code Online (Sandbox Code Playgroud)

如何将其转换为字符串 "\x01\x02\x03\x0A"

我使用的是Python 2.6.

python string byte

5
推荐指数
1
解决办法
1632
查看次数

如何使用C++中的模板编程从基类创建派生类?

我需要从基类创建许多类(超过50个),其中唯一的区别在于派生类的名称.

例如,我的基类定义为:

class BaseError : public std::exception
{
private:
    int osErrorCode;
    const std::string errorMsg;

public:
    int ec;
    BaseError () : std::exception(), errorMsg() {}

    BaseError (int errorCode, int osErrCode, const std::string& msg)
         : std::exception(), errorMsg(msg)
    {
       ec = errorCode;
       osErrorCode = osErrCode;
    }

    BaseError (const BaseError& other)
        : std::exception(other), errorMsg(other.errorMsg)
    {
        ec  = other.errorCode;
        osErrorCode = other.osErrorCode;
    }

    const std::string& errorMessage() const { return errorMsg; }

    virtual ~BaseError() throw(){}

}
Run Code Online (Sandbox Code Playgroud)

我必须从这个基类创建许多派生类,每个类都有自己的构造函数,复制构造函数和虚拟析构函数,目前我正在复制/粘贴代码,在必要时更改名称:

class FileError : public BaseError{
private:
    const std::string error_msg;

public: …
Run Code Online (Sandbox Code Playgroud)

c++ templates derived-class

2
推荐指数
1
解决办法
869
查看次数

标签 统计

python ×2

string ×2

byte ×1

c++ ×1

derived-class ×1

reference ×1

templates ×1