我正在设置python类,但它会在0x03391d90处打印<< strong> main .deteil对象
我试图在Google中进行搜索,但没有帮助我
Python类
class person:
def __init__(self,fname,lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class student(person):
def __init__(self,fname,lname,year):
person.__init__(self,fname,lname)
self.graduate_year = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, self.graduate_year)
class dateils(person):
def __init__(self,fname,lname, age, gender,):
person.__init__(self, fname, lname)
self.age = 17
self.gender = "male"
def student_details(self):
print(self.firstname, self.lastname, self.age,self, self.gender)
#Student
x = student("Enter your name:", "Enter your lastname: ", 2019)
x.welcome()
#person details
d = dateils(input("Enter your name"), input("Enter your lastname"), input("Enter your age"), input("Enter your gender"))
d.student_details()
我希望输入详细信息的输出信息,但实际输出是
输入的名称,输入的姓氏,输入的年龄,以及这个主要 .dateils对象为0x03391D90>男性
答案 0 :(得分:0)
在student_details
函数中,打印对象:
def student_details(self):
print(self.firstname, self.lastname, self.age,self, self.gender)
^
|
HERE ----------------------------------------------+
您没有在类内部实现__str__
和__repr__
函数,因此该函数将点打印到存储对象的内存中(这是基本行为)。您应该删除此self
或将其替换为self.graduate_year
,以正确打印所需的所有内容。
答案 1 :(得分:0)
*注意我正在运行python 3.6.7
如vurmux所述,您需要在类内部使用__str__
或__repr__
函数。发生的事情是python正在打印出对我们来说毫无意义的对象ID <main.dateils object at 0x03391D90>
。解决这个问题的奇怪方法如下所示。我实现了一个__repr__
函数,在其中定义了类dateils的实例(您可能想知道细节)。然后我输出结果。另外,我可能不确定您是否打算定义self.age = 17,但我将其保留不变,只修正了其中一部分。
class person:
def __init__(self,fname,lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class student(person):
def __init__(self,fname,lname,year):
person.__init__(self,fname,lname)
self.graduate_year = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, self.graduate_year)
class dateils(person):
def __init__(self,fname,lname, age, gender,):
person.__init__(self, fname, lname)
self.age =17
self.gender = "male"
def student_details(self):
print(self.firstname, self.lastname, self.age, self.gender)
def __repr__(self):
return str(self.firstname) + str(self.lastname) + str(self.age) + str(self.gender)
#Student
x = student("Enter your name:", "Enter your lastname: ", 2019)
x.welcome()
#person details
d = dateils(input("Enter your name"), input("Enter your lastname"), input("Enter your age"), input("Enter your gender"))
d.student_details()
有关以下两个 str 和 repr 的更多信息,请参见以下问题 Difference between __str__ and __repr__?