为什么我的程序会覆盖两个对象?

问题描述 投票:0回答:1

我正在编写一个程序来创建fakeduplicates,它在指定的属性中有某种不一致。

我正在使用我的班级“Firma”:

class Firma:
    def __init__(self, firma, strasse, plz, ort, telefon):
        self.firma = firma
        [...]

    def getFirma(self):
       return self.firma
        [...]

    def setFirma(self, firma):
      self.firma = firma
        [...]

    def toString(objekt) -> str:
        result = '"' + objekt.getFirma() + '"\t"' + objekt.getStrasse() + '"\t"' + objekt.getOrt() + '"\t"' + objekt.getPlz() + '"\t"' + objekt.getTelefon() + '"'
        return result

现在我写了这段代码来测试我的方法“createS schreibfehler”是否按照我想要的方式创建了一个错误。

for i in range(100):

    firma = Generator.generateFirma()

    x = firma
    y = firma

    AttributFirma = x.getFirma()
    fehlerString = Szenario.createSchreibfehler(AttributFirma)
    y.setFirma(fehlerString)

    print(Firmendatensatz.Firma.toString(x))
    print(Firmendatensatz.Firma.toString(y))

我得到一个输出像:

"Bohlnader" "Lachmannstr. 113"  "Bamberg"   "13669" "01991 351660"
"Bohlnader" "Lachmannstr. 113"  "Bamberg"   "13669" "01991 351660"
or 
"Carsetn"   "Seifertring 139"   "Delitzsch" "64621" "(00423) 19090"
"Carsetn"   "Seifertring 139"   "Delitzsch" "64621" "(00423) 19090"
...

(两个字符串(x和y)都有拼写错误)(创建Firma我正在使用Faker包)

一切正常,但是当我使用y.setFirma(fehlerString)时它似乎覆盖了我的x和y。

你们是否知道为什么x和y中存在错误,而不仅仅是我的变量x?我在JetBrains PyCharm中使用Python 3.7.1

python faker
1个回答
0
投票

您没有通过执行创建两个独立的对象

firma = Generator.generateFirma()

x = firma
y = firma

xy是引用相同对象数据的名称。您对x所做的任何更改都是根据​​y也引用的数据完成的。

这是使用可变对象时的典型初学者错误 - 主要使用列表:

如果您不需要访问器方法,请删除它们,它们只会使您的结构复杂化。您可以创建一个简单的clone-ing方法,创建对象的独立实例并使用它:

class Firma:
    def __init__(self, firma, strasse, plz, ort, telefon):
        self.firma = firma
        self.strasse = strasse 
        self.plz = plz
        self.ort = ort
        self.telefon = telefon

    def CloneMe(self):
        """Returns a clone of this object as independent copy."""
        return Firma(self.firma,self.strasse,self.plz,self.ort,self.telefon)


    def __str__(self):
        # default string method so you can simply print() your object-instances
        return f'"{self.firma}"\t"{self.strasse}"\t"{self.plz}"\t"{self.ort}"\t"{  self.telefon}"'

x = Firma("A", "cstr 42", "4444", "NoWhere"," 0123456789")

# clone and change something

y = x.CloneMe()    
y.ort = "Muenchen"     # no need for get/set methods 

print(x, "=>", id(x))
print(y, "=>", id(y))

输出(不同的数据,不同的ID):

"A" "cstr 42"   "4444"  "NoWhere"   " 0123456789" => 139652937418232   # x
"A" "cstr 42"   "4444"  "Muenchen"  " 0123456789" => 139652937418288   # y
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.