Issue
how to add two dict in cs list
I want to add two dictionaries to the cs list in the addcoursess function, but it gives an error Text error: takes 1 positional argument but 2 were given
mainlist:
cs = [
{
"title": "Python",
"teacher": "Amiri",
},
{
"title": "HTML",
"teacher": "Dehyami",
},
{
"title": "PHP",
"teacher": "Enayati"
}
]
class User:
def __init__(self, fisrtname, lastname):
self.fname = fisrtname
self.lname = lastname
def fullname(self):
print(f"my fullname is {self.fname} {self.lname}")
class Student(User):
def __init__(self, fisrtname, lastname, email):
super().__init__(fisrtname, lastname)
self.email = email
self.coursess = []
def fullname(self):
print("i am an student")
super().fullname()
def printcoursess(self):
if self.coursess:
for course in self.coursess:
print("Coursess : " + course["title"])
else:
print("There is no course")
Here is the class in which it is error
class Teacher(User):
def __init__(self, fisrtname, lastname, code):
super().__init__(fisrtname, lastname)
self.code = code
def addcoursess(item):
dict = {}
dict.update(item)
cs.append(dict)
print(dict)
def fullname(self):
print("i am an teacher")
super().fullname()
t1 = Teacher("abolfazl", "zaker", 3223)
addcoursess function here
t1.addcoursess({"title": "Java", "teacher": "ganjeali"})
print(cs)
Solution
U miss the self
argument in the function definition. Your Teacher class should look like this:
class Teacher(User):
def __init__(self, fisrtname, lastname, code):
super().__init__(fisrtname, lastname)
self.code = code
def addcoursess(self, item):
dict = {}
dict.update(item)
cs.append(dict)
print(dict)
def fullname(self):
print("i am an teacher")
super().fullname()
Or if u don't want to pass the self
, the class should be defined with the @staticmethod
decorator like this:
class Teacher(User):
def __init__(self, fisrtname, lastname, code):
super().__init__(fisrtname, lastname)
self.code = code
@staticmethod
def addcoursess(item):
dict = {}
dict.update(item)
cs.append(dict)
print(dict)
def fullname(self):
print("i am an teacher")
super().fullname()
Info about static method are here: https://docs.python.org/3/library/functions.html#staticmethod
Answered By - Mattia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.