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

Python类跨方法访问变量报错NameError,求解决方法

Fixing the NameError: Accessing newyork_info in the state() Method

Hey there! The issue here is that newyork_info is a local variable inside your __init__ method—meaning it only exists within the scope of that method, and can't be accessed from other methods like state().

To fix this, you need to turn newyork_info into an instance attribute by prefixing it with self.. Instance attributes are tied to the object instance itself, so they’re accessible across all methods of the class.

Here's the corrected code:

import Another_class
class Some_class:
    def __init__(self, city):
        self.city = city
        self.newyork_info = None  # Initialize with a default value first
        if self.city == "newyork":
            self.newyork_info = Another_class(some_param)  # Assign as instance attribute
    def state(self):
        if self.city == "newyork":
            if self.newyork_info is not None:  # Add a safety check
                newyork_weather = self.newyork_info.get_weather()
                newyork_population = self.newyork_info.get_population()

A few key notes:

  • By using self.newyork_info, we’re storing the Another_class instance as part of the Some_class object, so state() can access it anytime.
  • I added self.newyork_info = None at the start of __init__ to ensure the attribute exists even when city isn’t "newyork"—this prevents another potential AttributeError if someone calls state() with a different city.
  • The safety check in state() (if self.newyork_info is not None) is a good practice to avoid trying to call methods on a None value.
  • I also fixed a small typo: get_wether should be get_weather—easy mistake to make!

内容的提问来源于stack exchange,提问作者sung chul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:24:51