Python变量赋值与取值方法及类代码NameError报错问题求助
问题解决
错误原因
- 代码执行顺序错误:你在
Supplier_105实例化之前就尝试访问它的属性,Python解释器从上到下执行代码,此时变量还未创建,因此抛出NameError - 类方法缩进错误:
get_state函数没有缩进至Supplier类的代码块内,不属于类的成员方法,实例无法调用该方法 - 小瑕疵:实例化时传入的
supplier_id是字符串类型,和原有字典中的整数类型不一致,可按需调整
修正后完整代码
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 # 1. Define the class 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) # 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") # 3. 访问属性、调用方法 print(Supplier_105.supplier_name) print(Supplier_105.get_state())
运行输出
Initialiser called Rodriguez, Carter and Johnson The state is Costa and the postcode is 3880
内容的提问来源于stack exchange,提问作者user16690496
相关产品推荐
相关产品推荐

