문제 설명
학생의 이름을 인쇄하려고 하는 것이 잘못된 것은 무엇입니까? (What is wrong with trying to print the name of the student?)
이것은 내 코드입니다. 학생 이름을 인쇄하려고 했지만 오류가 많이 발생했습니다. 내가 뭘 잘못했어? 감사합니다!
class Elev:
"""
Un elev are nume, cnp,clasa,
"""
def __init__(self,nume,cnp,clasa):
self.nume=nume
self.cnp=cnp
self.clasa=clasa
def set_nume(self,nume):
self.nume=nume
def get_nume(self):
return self.nume
def set_clasa(self,clasa):
self.clasa=clasa
def get_clasa(self):
return self.clasa
def set_cnp(self,cnp):
self.cnp=cnp
def get_cnp(self):
return self.cnp
def merg(self):
print("Merge la ore")
def __str__(self):
return "%s"(self.nume)
이것은 내가 사용한 두 번째 클래스입니다.
class Student(Elev):
def __init__(self,nume,cnp,an):
self.an=an
super().__init__(self,nume,cnp)
def Vacanta(self):
print("Nu ai restanta ai vacanta!!!!!")
여기에 클래스와 함수를 호출한 방법이 나와 있습니다.
def Main():
student=Student("Popescu Vasile",232423423,1)
print(student.get_nume())
Main()
오류는 다음과 같습니다.
Traceback (most recent call last): File "D:/Facultate/Python/tema_mostenire/tema_mostenire.py", line 36, in <module> Main() File "D:/Facultate/Python/tema_mostenire/tema_mostenire.py", line 34, in Main print(student.get_nume()) File "D:/Facultate/Python/tema_mostenire/tema_mostenire.py", line 24, in str return "%s"(self.nume) TypeError: 'str' object is not callable
참조 솔루션
방법 1:
Your __str__
method is missing the %
operator:
def __str__(self):
return "%s" % (self.nume)
If you used proper style, with a space between operators, this would have been easier to see.
방법 2:
From the error you got ,it looks like the problem was the last function of the class.See below:
class Elev:
"" Un elev are nume, cnp,clasa, """
def __init__(self,nume,cnp,clasa): self.nume=nume self.cnp=cnp self.clasa=clasa
def set_nume(self,nume): self.nume=nume
def get_nume(self):
return self.nume
def set_clasa(self,clasa): self.clasa=clasa
def get_clasa(self):
return self.clasa
def set_cnp(self,cnp):
self.cnp=cnp
def get_cnp(self):
return self.cnp
def merg(self):
print("Merge la ore")
def __str__(self):
return "%s" % (self.nume) #fixed
방법 3:
Beside the indentation there's two issues with your code:
def __str__(self):
return "%s"(self.nume)
Above is not valid Python code, you can either add %
operator as Daniel suggested or you can just modify it to return the name:
def __str__(self):
return self.nume
The second issue is with the way you call parent class constructor here:
def __init__(self,nume,cnp,an):
self.an=an
super().__init__(self,nume,cnp)
When super
is called without parameters you don't need to supply self
parameter but you need to supply all three other parameters that parent expects:
def __init__(self,nume,cnp,an):
self.an=an
super().__init__(nume,cnp, 'foo')
(by Mary、Daniel Roseman、Taufiq Rahman、niemmi)