【发布时间】:2018-08-27 09:31:37
【问题描述】:
我有一个问题。我正在学习 Python 并试图理解超类、子类和它们之间的层次结构。我有一件事我不完全理解。 我正在尝试编写一个程序,其中有一个“Person”超类和“Birthday”子类。我为它们定义了 init 方法。我想要做的是,我想创建一个实例的人。同时它应该为生日创建相同的实例。因为所有人都有生日:) 我想使用我在“生日”类中定义的方法。 代码;
import datetime
class Person(object):
def __init__(self,name):
self.name=name
Birthday.__init__(self,name)
def gender(self,gender):
self.gender=gender
class Birthday(Person):
def __init__(self,name):
self.objectlike=[]
self.birthday=None
self.youget={}
def setbirth(self,year,month,day):
self.birthday=datetime.date(year,month,day)
def getbirth(self):
return self.birthday
def __str__(self):
return self.name
def setyouget(self,year,thing):
self.youget[year]=thing
def setlikeob(self,thing):
self.objectlike.append(thing)
def nextbirth(self):
thisyearbirth=getbirth().year.replace(year=datetime.date.today().year)
return thisyearbirth
def howlong(self):
return self.nextbirth()-datetime.date.today()
def getage(self):
age=datetime.date.today().year-self.birthday.year
return age
问题是当我创建一个 Person 实例时,例如,
joey=Person('Joey Tribiani')
然后我尝试为乔伊设置生日;
joey.setbirth(1980,5,5)
它说:'Person' 对象没有属性 'setbirth'
我该如何克服这个问题?我想我应该在 init 方法中添加一些代码,但我不知道要添加什么。我在 Person 类中添加了“Birthday.init(self,name)”但是没用。
(顺便说一句,这是我的第一个问题。我在这个网站上阅读了很多主题。我对使用它的人的帮助感到惊讶。)
【问题讨论】:
-
为什么
Birthday是Person的子类? -
继承另一个的类得到了别人的方法,而不是相反。也请阅读this
-
另外,好的 Python 代码不使用 getter 和 setter。
-
@khelwood 你能给我指出一个资源,上面写着“好的 Python 代码不使用 getter 和 setter”并说明原因吗?
-
我假设他们在谈论@property,它实际上是一个getter,它实际上有一个setter;所以也许更好的措辞是 python 对 getter 和 setter 有更好的结构。