I have no idea what is wrong! This is a very simple program and I have done a lot head banging! Please someone enlighten me!
This a lab problem from the CSE 111 – Programming Language II course. They teach Java at the university and the code I wrote in Java works fine.
I just have to create a Student class with some fields to hold the basic information about a student with methods to get and set the attributes. Then create an instance of that class and tryout the methods.
But every time I run this program the following error occurs:
TypeError: set_name() takes exactly 1 positional argument (2 given)
Here is the code I wrote.
class Student:
'''Student class'''
name = None
id = 0
address = None
cgpa = None
def get_name():
return name
def set_name(n):
name = n
def get_id():
return id
def set_id(i):
id = i
def get_address():
return address
def set_address(a):
address = a
def get_cgpa():
return cgpa
def set_cgpa(c):
cgpa = c
#An object of Student class
jack = Student()
jack.set_name('jacky')
print(jack.get_name())
You’re not accepting a reference to your instance as the first argument to that method, i.e. your
set_name()should be written:This is somewhat different from other languages where there is a built-in keyword (such as
this) that refers to the current object. Python passes that reference explicitly, as an argument to the method.All your other methods must be modified similarly.
Note that just setting
name = nsets a local variablenamewhich goes away when the method ends; it does not set anything on the instance. You have to explicitly setself.nameif you want an instance attribute.Also, and this is a matter of style, but you do not usually write
setandgetmethods in Python. It is normal practice to set and get attributes directly. If you want to do validation of values, use a property instead. So basically, none of your methods are actually necessary in good style.However, you don’t have an
__init__()method. Usually you would pass the desired attributes of the instance when instantiating the class and save these on the instance.