program is:
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()
CodePudding user response:
Your main problem is that you are calling self.displval
before you set the attributes it tries to display.
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)
However, __init__
is doing too much work. It should receive values as arguments and simply set the attributes. If you want Stud
to provide a way to collect those arguments from the user, define an additional class method. (It's also debatable whether __init__
should be printing anything to standard output, but I'll leave that for now.)
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()
CodePudding user response:
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()
Put the self.displval()
at the end. You're calling it before it has any self.[value]
to pass into the method.