You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:27:00