【问题标题】:Can't find a class variable in python [closed]在python中找不到类变量[关闭]
【发布时间】:2023-03-03 01:30:01
【问题描述】:

所以我目前正在为一个项目编写一个简单的设置页面......所以页面看起来是这样的:

class Settings(object):
   def _init_(self):
       self.screen_width = 1200
       self.screen_height = 800
       self.bg_color = (230,230,230)

st = Settings()
print(st.screen_width)

所以我按照其他问题的说明进行操作: Accessing a class' member variables in Python? 但我仍然无法访问单个变量...

这是我得到的错误:

它基本上说当前类(即“设置”)没有名为“screen_width”的属性

我开始认为它是我的文本编辑器...我使用 VSCode 但我不知道可能遗漏了什么?

【问题讨论】:

    标签: python attributeerror


    【解决方案1】:

    你犯了一个小错误..在你的初始化函数中它应该是__init__而不是_init_

    class Settings(object):
       def __init__(self):
          self.screen_width = 1200
          self.screen_height = 800
          self.bg_color = (230,230,230)
    
    st = Settings()
    print(st.screen_width)
    

    【讨论】:

      【解决方案2】:

      拼写错误的__init___init_应替换为__init__

      class Settings(object):
         def __init__(self):  # <---
             self.screen_width = 1200
             self.screen_height = 800
             self.bg_color = (230,230,230)
      

      【讨论】:

        【解决方案3】:

        这里你在 int 函数中犯了错误 这个瞬间

        def _init_(self):
        

        更改为 def int(自我)

        【讨论】:

          猜你喜欢
          • 2022-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多