"班级应该用名字和生日来初始化,但生日应该是无。" "应该有两种方法,名称和生日" " setBirthday将他们的生日设置为日期"这些是我给出的指示,这是较大图片中的一小部分。
我试图设置用户输入的日期,月份和年份...稍后将用于其他计算..
代码:
class person(object):
def __init__(self, name):
self.name = name
self.setBirthday = None
#getName returns the name of the person
def getName(self):
return self.name
#setBirthday sets their Birthday to a date
def setBirthday(self):
day = (raw_input('Please enter the date of the month you were born on here ->'))
return self.day
month = (raw_input('Please enter the month of the year you were born on here ->'))
return self.month
year = (raw_input('Please enter the year you were born on here ->'))
return self.year
varName = person(raw_input('Please enter your name here ->'))
varDate = person.setBirthday()
你能指出我正确的方向吗?这类课程让我感到困惑......我需要让用户能够输入要保存以供日后使用的日,月和年。错误在评论中。我确实删除了代码中的返回值。
答案 0 :(得分:2)
setBirthday
定义为方法,但只要您实例化该方法,该方法就会消失,setBirthday
只指向None
。请注意,birthday
和setBirthday
是两个唯一的名称,该类已经在后者中使用该方法。var = (input())
不是这样的场合。@property
装饰器标记的方法)。MyClass.methodname()
,你需要传递一个类的实例。这就是标准Python样式(PEP-8)要求类名为Uppercase
或UpperCase
以及其他对象为lowercase
或snake_case
的原因。命名类person
使它看起来像某个实例,当它实际上是一个类时,很容易误用它。以下是代码的样子:
class Person(object):
def __init__(self, name):
self.name = name
self.birthday = None
def getName(self):
'''return the name of the person'''
# this method should be removed. to get a person's name,
# use "person.name" instead of "person.getName()"
return self.name
def setBirthday(self):
'''set their Birthday to a date'''
day = raw_input('Please enter the date of the month you were born on here ->')
month = raw_input('Please enter the month of the year you were born on here ->')
year = raw_input('Please enter the year you were born on here ->')
self.birthday = int(day), int(month), int(year)
person = Person(raw_input('Please enter your name here ->'))
person.setBirthday()