Python 2.7类,用户输入出生日期用于将来使用

2024-09-30 16:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

类应该用一个名字和一个生日初始化,但是生日不应该是None 应该有两种方法,名字和生日 “挫折日将他们的生日定为一个日期”这是我得到的指示,这是大图中的一小部分。在

我正在尝试设置用户输入的日期、月份和年份…这将在以后用于其他计算。。在

代码:

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()

你能给我指出正确的方向吗?这个类的东西真的让我困惑…我需要让用户能够输入日,月和年,以备日后使用。错误在下面的注释中。我确实删除了代码中的返回。在


Tags: ofthenameselfinputrawreturnhere
1条回答
网友
1楼 · 发布于 2024-09-30 16:34:44
  1. 您的类将setBirthday定义为一个方法,但是一旦实例化该类,该方法就会消失,setBirthday只指向None。注意,birthday和{}是两个唯一的名称,并且该类已经将后者用于该方法。在
  2. 你有不必要的括号。尽量只使用分组所需的内容,为清晰起见,偶尔需要额外的一对。var = (input())不是这样的场合。在
  3. Python不需要getter和setter。没有私有变量这样的东西,所以任何想要修改的人都可以随心所欲地修改。我所知道的唯一不能被重新定义的是一个属性(一个用@property修饰符标记的方法)。在
  4. 你在混淆实例变量和全局变量,以及何时将它们转换成另一个变量。该类中的setter应该简单地设置实例变量,而不是将它们返回给调用者(在Java中也是如此,这实际上就是使用getter和setter的地方)。在
  5. 当您直接调用一个类的实例方法时,比如MyClass.methodname(),您需要向它传递一个类的实例。这就是为什么标准Python样式(PEP-8)要求类名为Uppercase或{},其他对象为lowercase或{}。将类命名为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()

相关问题 更多 >