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 theAnother_classinstance as part of theSome_classobject, sostate()can access it anytime. - I added
self.newyork_info = Noneat the start of__init__to ensure the attribute exists even whencityisn’t "newyork"—this prevents another potentialAttributeErrorif someone callsstate()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 aNonevalue. - I also fixed a small typo:
get_wethershould beget_weather—easy mistake to make!
内容的提问来源于stack exchange,提问作者sung chul
相关产品推荐
相关产品推荐

