无法使用属性在python 3中复制对象

时间:2017-08-18 22:44:40

标签: python-3.x oop

我在python中使用了一些具有动态属性的对象,所有对象都带有数字和字符串。我还创建了一个简单的方法来制作一个对象的副本。其中一个属性是列表,但我不需要对其进行深层复制。这种方法似乎工作正常,但我发现了一个奇怪的问题。这段代码显示了它:

#!/usr/bin/env python3

# class used for the example
class test(object):

    def copy(self):
        retval = test()
        # just create a new, empty object, and populate it with
        # my defined properties
        for element in dir(self):
            if element.startswith("_"):
                continue
            setattr(retval, element, getattr(self, element))
        return retval

test1 = test()
# here I dynamically create an attribute (called "type") in this object
setattr(test1, "type", "A TEST VALUE")
# this print shows "A TEST VALUE", as expected
print(test1.type)
# Let's copy test1 as test2
test2 = test1.copy()
# this print shows also "A TEST VALUE", as expected
print(test2.type)
test2.type = "ANOTHER VALUE"
# this print shows "ANOTHER VALUE", as expected
print(test2.type)
# Let's copy test2 as test3
test3 = test2.copy()
# this print shows "A TEST VALUE", but "ANOTHER VALUE" was expected
print(test3.type)

我的概念错误在哪里?

感谢。

2 个答案:

答案 0 :(得分:2)

您的copy()方法从copy复制了test1方法(不是该类中的函数),这意味着self在{ {1}}仍为test2.copy()

答案 1 :(得分:1)

如果您查看class Player: public sf::Sprite ,您会看到其中一个元素是dir(test1)。换句话说,您不只是复制'copy'属性。

您正在复制type方法。

copytest2设置为test2.copy,这是一种将test1.copy复制的绑定方法。

不要使用test1。查看实例的dir,它只包含特定于实例的数据。