如何在Python类中添加set方法修改Supplier实例的postcode属性值
你只需要在Supplier类中新增一个专门用于修改postcode属性的实例方法即可,具体实现如下:
实现步骤
- 在
Supplier类内部定义set_postcode方法,接收新的邮政编码作为入参,将其赋值给实例的postcode属性即可,也可根据需求增加入参合法性校验逻辑。 - 实例化类之后调用该方法,传入目标值
4980就可以完成修改。
完整修改后的代码示例
supplier_105 = { "city": "Port Bradley", "contact_firstname": "Brittany", "contact_lastname": "Costa", "contact_title": "Mrs", "country": "Australia", "email": "brittany8706.costa@gmail.com", "notes": "", "phone": "(08) 6939 8022", "postcode": "3880", "state": "Costa", "street_address": "6/81 Heather Rosebowl", "supplier_id": 105, "supplier_name": "Rodriguez, Carter and Johnson", } # Write your code here class Supplier: def __init__( self, city, contact_firstname, contact_lastname, contact_title, country, email, notes, phone, postcode, state, street_address, supplier_id, supplier_name, ): print("Initialiser called") self.city = city self.contact_firstname = contact_firstname self.contact_lastname = contact_lastname self.contact_title = contact_title self.country = country self.email = email self.notes = notes self.phone = phone self.postcode = postcode self.state = state self.street_address = street_address self.supplier_id = supplier_id self.supplier_name = supplier_name def get_state(self): return "The state is {} and the postcode is {}".format(self.state, self.postcode) # 新增的修改postcode的方法 def set_postcode(self, new_postcode): # 可选校验:澳大利亚邮政编码为4位数字,可根据实际规则调整 if isinstance(new_postcode, str) and len(new_postcode) == 4 and new_postcode.isdigit(): self.postcode = new_postcode else: raise ValueError("传入的邮政编码不合法,应为4位数字字符串") # 2. 实例化类 Supplier_105 = Supplier( "Port Bradley", "Brittany", "Costa", "Mrs", "Australia", "brittany8706.costa@gmail.com", "", "(08) 6939 8022", "3880", "Costa", "6/81 Heather Rosebowl", "105", "Rodriguez, Carter and Johnson", ) print(Supplier_105.supplier_name) # 3. 调用原有方法 print(Supplier_105.get_state()) # 修改postcode为4980 Supplier_105.set_postcode("4980") # 验证修改结果 print(Supplier_105.get_state())
运行效果
调用set_postcode("4980")后再次调用get_state(),即可看到postcode已经更新为4980。
内容的提问来源于stack exchange,提问作者user16691147
相关产品推荐
相关产品推荐

