I'm new to classes in python. I've been trying to make a class that has a list t
inside of it and each item of that list contains another class. For example, a class with the name student
which contains two variables (student_name
, mark
). Here is my code:
def RempClasse(y):
for i in range(3):
y.t[i].nom = input("nom du elevel")
y.t[i].moyen = float(input("moyenne du elevel"))
for i in range(3):
print(y.t[i].nom)
print(y.t[i].moyen)
class eleve :
nom = ""
moyen = float()
class classe :
t=[[eleve] for i in range(3)]
print(RempClasse(classe))
The problem is, it keeps giving me this error when I type the input for nom du elevel
:
Traceback (most recent call last):
File "/path/to/code.py", line 13, in <module>
print(RempClasse(classe))
File "/path/to/code.py", line 3, in RempClasse
y.t[i].nom = input("nom du elevel")
AttributeError: 'list' object has no attribute 'nom'
CodePudding user response:
If you want to learn about class
es you might want to consider reading something like this or this already suggested in the comments.
Nevertheless, your problem was
a.) that you use the class
es without creating instances of it. Defining a class
with class eleve:
as you did is only the first part, next you have to create an instance (e.g., eleve()
), which then can be used as other objects in Python. Just writing eleve
just refers to the class, which is something like a template for instances. However, you want instances as those carry the values you assign to them (e.g., when assigning some input to .nom
).
b.) By adding the[ ... ]
around eleve
, your create a list
with one element in a list
that contains three such list
s. Thus when calling y.t[i]
in your code, you get a list
. In that list
is an object that has the attribute you want to call. Just removing this brackets creates a list
of instances or objects, you can work with.
Below is a working example, however, this is not what object-oriented programming is intended for. I strongly recommend that you read first about object-oriented programming before proceeding.
def RempClasse(y):
for i in range(3):
y.t[i].nom = input("nom du elevel")
y.t[i].moyen = float(input("moyenne du elevel"))
for i in range(3):
print(y.t[i].nom)
print(y.t[i].moyen)
class eleve :
nom = ""
moyen = float()
class classe :
t=[eleve() for i in range(3)]
print(RempClasse(classe))