我列表中的数据被输入的新数据覆盖

时间:2018-09-14 03:16:24

标签: python python-3.x class oop enums

嘿,我是Python的新手,只是想学习和增强我的编程技能,而且我似乎无法理解为什么我的列表输出打印错误。 它应该打印出: "Property Type: House""Purchase Type: purchase"。紧随其后,应打印出"Property Type: Apt""Purchase Type: rental",但它会打印两次公寓和租金,并忽略添加的第一对信息。似乎无法理解为什么这样做。如果有人可以提供帮助,我将不胜感激。

class Agent:

    def __init__(self):
        self.properties = []

    def add_new_property(self, property_type, purchase_type):
        self.prop_type = property_type
        self.pur_type = purchase_type
        self.properties.append(self)

    def print_properties(self):
        for property in self.properties:
            print("Property Type: " + property.prop_type)
            print("Purchase Type: " + property.pur_type)

a = Agent()
a.add_new_property("house", "purchase")
a.add_new_property("apt", "rental")
a.print_properties()

2 个答案:

答案 0 :(得分:0)

如上所述,您将意识到您正在将对象附加到自身,因此我们需要附加对象的副本而不是自身。这样可以确保指向对象及其副本的指针不同。因此,在更新对象之后,我们仍然保留其先前的副本

班级代理:

def __init__(self):
    self.properties = []

def add_new_property(self, property_type, purchase_type):
    from copy import copy
    self.prop_type = property_type
    self.pur_type = purchase_type
    self.properties.append(copy(self))

def print_properties(self):
    for property in self.properties:
        print("Property Type: " + property.prop_type, end = '\t\t')
        print("Purchase Type: " + property.pur_type)


a = Agent()
a.add_new_property("house", "purchase")
a.add_new_property("apt", "rental")
a.print_properties()

Property Type: house            Purchase Type: purchase
Property Type: apt              Purchase Type: rental

答案 1 :(得分:-1)

一个主意,如果您使用字典,则可以像这样缩减代码

class Agent:

    def __init__(self):
        self.props = {}

    def add_new_property(self, prop_type, buy_type):
        self.props[prop_type] =  buy_type

    def print_properties(self):
        for k, v in self.props.items():
            print(f"Property Type: {k}".ljust(20),f"Purchase Type: {v}")

a = Agent()
a.add_new_property("house", "purchase")
a.add_new_property("apt", "rental")
a.print_properties()

输出

(xenial)vash@localhost:~/python$ python3.7 class.py
Property Type: house Purchase Type: purchase
Property Type: apt   Purchase Type: rental