我几乎是Python的新手,我目前正在尝试在线发现以前的学校项目。在运行代码以测试该类是否有效时,NameError
出现了,即使我已经通过许多问题搜索了几个小时没有运气 - 这可能只是我。
class customers:
__id = ""
__email =""
__forename = ""
__surname = ""
__DOB = ""
__address = ""
__history = []
def __init__(self, id, email, forename,surname, DOB, address, history):
self.__id = id
self.__email = email
self.__forename = forename
self.__surname = surname
self.__DOB = DOB
self.__address = address
self.__history = history
def set_id(self, id):
self.__id = id
tyler_k = customers("001")
错误发生在最后一行,说明customers
也未定义。这个程序的目的是能够搜索并添加到我的书和教程所涵盖但我无法修复的customers
类。谢谢你,随时可以指导我以前的任何问题。
答案 0 :(得分:1)
不确定为什么你会得到NameError,但是因为你是python的新手,所以你的代码是用注释修复的一个例子。
from datetime import date
# Your classnames should be CamelCased (words should start with capital letters)
# Also, the classname here should be singular because it represents one Customer, rather than a list of Customers
class Customer:
# making variables here would create class variables (they would be shared by all instances of Customers). So delete these.
# Note the indentation, in order for this method to be recognized as part of the class, it must be indented within the class.
def __init__(self, id, email, forename,surname, DOB, address, history):
# This will create and assign your member variables.
self.__id = id
self.__email = email
self.__forename = forename
self.__surname = surname
self.__DOB = DOB
self.__address = address
self.__history = history
def set_id(self, id):
self.__id = id
tylers_bday = date(2016, 5, 4)
# Parameters must match on a one-to-one basis with the parameters of your constructor (the __init__ method above).
tyler_k = Customer("001", "tyler_k@gmail.com", "tyler", "Mr.", tylers_bday, "tylers address here", "Tylers history?")
答案 1 :(得分:0)
试试这个:
class customers:
__id = ""
__email =""
__forename = ""
__surname = ""
__DOB = ""
__address = ""
__history = []
def __init__(self, id, email, forename,surname, DOB, address, history):
self.__id = id
self.__email = email
self.__forename = forename
self.__surname = surname
self.__DOB = DOB
self.__address = address
self.__history = history
def set_id(self, id):
self.__id = id
tyler_k = customers("001", None, None, None, None, None, None)