AttributeError: 'Stud' object has no attribute 'sno' at line no.11
AttributeError: 'Stud' object has no attribute 'sno' at line no.11
节目是:
class Stud:
def __init__(self):
self.displval()
print("I am Constructor")
self.sno = int(input("Enter the roll number"))
self.sname = (input("Enter the Name"))
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
so = Stud()
您的主要问题是您在设置它试图显示的属性之前self.displval
调用。
class Stud:
def __init__(self):
print("I am Constructor")
self.sno = int(input("Enter the roll number"))
self.sname = (input("Enter the Name"))
self.displval()
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
但是,__init__
做的工作太多了。它应该接收值作为参数并简单地设置属性。如果您希望 Stud
提供一种从用户那里收集这些参数的方法,请定义一个额外的 class 方法。 (__init__
是否应该将任何内容打印到标准输出也值得商榷,但我暂时保留它。)
class Stud:
def __init__(self, sno, sname):
self.sno = sno
self.sname = sname
self.displval()
@classmethod
def create_with_user_input(cls):
sno = int(input("Enter the roll number"))
sname = (input("Enter the Name"))
return cls(sno, sname)
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
so = Stud.create_from_user_input()
class Stud:
def __init__(self):
print("I am Constructor")
self.sno = int(input("Enter the roll number"))
self.sname = (input("Enter the Name"))
self.displval()
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
so = Stud()
把self.displval()
放在最后。你在它有任何 self.[value]
传递给方法之前调用它。
节目是:
class Stud:
def __init__(self):
self.displval()
print("I am Constructor")
self.sno = int(input("Enter the roll number"))
self.sname = (input("Enter the Name"))
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
so = Stud()
您的主要问题是您在设置它试图显示的属性之前self.displval
调用。
class Stud:
def __init__(self):
print("I am Constructor")
self.sno = int(input("Enter the roll number"))
self.sname = (input("Enter the Name"))
self.displval()
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
但是,__init__
做的工作太多了。它应该接收值作为参数并简单地设置属性。如果您希望 Stud
提供一种从用户那里收集这些参数的方法,请定义一个额外的 class 方法。 (__init__
是否应该将任何内容打印到标准输出也值得商榷,但我暂时保留它。)
class Stud:
def __init__(self, sno, sname):
self.sno = sno
self.sname = sname
self.displval()
@classmethod
def create_with_user_input(cls):
sno = int(input("Enter the roll number"))
sname = (input("Enter the Name"))
return cls(sno, sname)
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
so = Stud.create_from_user_input()
class Stud:
def __init__(self):
print("I am Constructor")
self.sno = int(input("Enter the roll number"))
self.sname = (input("Enter the Name"))
self.displval()
def displval(self):
print("="*50)
print(self.sno)
print(self.sname)
so = Stud()
把self.displval()
放在最后。你在它有任何 self.[value]
传递给方法之前调用它。