builtins.NameError: 名称 'self' 未定义

0 投票
1 回答
2464 浏览
提问于 2025-04-18 17:33

在Windows 7上使用Python 3。

import pickle
import os.path
from tkinter import * # Import tkinter
import tkinter.messagebox   

class Places:
  def __init__(self, name, street, city, state, zip):
    self.name = name
    self.street = street
    self.city = city
    self.state = state
    self.zip = zip

class PlacesBook:
  def __init__(self):      
    window = Tk() # Create a window
    window.title("PlacesBook") # Set title

我在“class PlacesBook:”这一行遇到了错误,提示是builtins.NameError: name 'self' is not defined。

1 个回答

-3

问题出在你的缩进上。在Python中,缩进非常重要,它用来定义代码的结构,比如哪些代码属于类、方法等等。

还有一点,如果你使用Python 3,所有的类都必须继承自对象(object)。

import pickle
import os.path
from tkinter import * # Import tkinter
import tkinter.messagebox

class Places(object):
    def __init__(self, name, street, city, state, zip):
        self.name = name
        self.street = street
        self.city = city
        self.state = state
        self.zip = zip

class PlacesBook(object):
    def __init__(self):
        window = Tk() # Create a window
        window.title("PlacesBook") # Set title

撰写回答