小编Eri*_*F89的帖子

在哪种情况下,相同的字符串共享相同的引用?

我已经搜索了网络和堆栈溢出问题,但无法找到这个问题的答案.我所做的观察是,在Python 2.7.3中,如果为两个变量分配相同的单个字符串,例如

>>> a = 'a'
>>> b = 'a'
>>> c = ' '
>>> d = ' '
Run Code Online (Sandbox Code Playgroud)

然后变量将共享相同的引用:

>>> a is b
True
>>> c is d
True
Run Code Online (Sandbox Code Playgroud)

对于一些较长的字符串也是如此:

>>> a = 'abc'
>>> b = 'abc'
>>> a is b
True
>>> '  ' is '  '
True
>>> ' ' * 1 is ' ' * 1
True
Run Code Online (Sandbox Code Playgroud)

但是,在很多情况下,参考是(意外地)不共享:

>>> a = 'a c'
>>> b = 'a c'
>>> a is b
False
>>> …
Run Code Online (Sandbox Code Playgroud)

python string reference immutability

9
推荐指数
3
解决办法
433
查看次数

如何将构造函数方法传递给另一个方法并在那里调用它?

我试图避免在两个类的克隆方法中重复相同的代码,一个继承自另一个类.我目前的方法是将两个类共有的代码放在基类的(非静态)克隆方法中,并从扩展类中调用它.为此,我试图将扩展类的构造函数传递给基类,以便可以在那里调用它.这是我目前正在做的一个简化示例:

class S(object):
    """Base class"""
    def __init__(self):
        self.a = 0

    def clone(self, constructor=None):
        if constructor is None:
            constructor = self.__init__
        cloned = constructor()
        # Expecting: cloned.a = 1, cloned.b = 7

        assert cloned is not None  # raises AssertionError
        cloned.a = self.a  # Set a to 2
        return cloned

class C(S):
    """Child class, extending Base"""
    def __init__(self):
        self.a = 1
        self.b = 7

    def clone(self):
        cloned = super(C, self).clone(self.__init__)
        # Expecting: cloned.a = 2, cloned.b = 7

        cloned.b = self.b …
Run Code Online (Sandbox Code Playgroud)

python methods inheritance

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

标签 统计

python ×2

immutability ×1

inheritance ×1

methods ×1

reference ×1

string ×1