1

I started learning python. Here is a simple program:

class StudentRepo:
    def __init__(self):
        self.student_list = []

    def add(self, student):
        self.student_list.append(student)

    def get_list(self):
        self.student_list




class Student:
    def __init__(self, name, age):
        self.age = age
        self.name = name




from models.student.Student import Student
from services.student.StudentRepo import StudentRepo

s1 = Student("A", 10)
s2 = Student("B", 11)

# What is the issue here ?
StudentRepo.add(s1)
StudentRepo.add(s2)

studentList = StudentRepo.get_list()
for student in studentList:
    print(student.name)

What is the issue with s1 = Student("A", 10) ?

Manish Kumar
  • 10,214
  • 25
  • 77
  • 147
  • 4
    It would be helpful if you post the exception you are receiving because you describe the issue is with `s1 = Student("A", 10)` but it looks like the issue you are having is because you haven't created an instance of `StudentRepo` you are calling directly on the class. – AChampion Apr 17 '18 at 04:23
  • Possible duplicate of [Python class static methods](https://stackoverflow.com/questions/12735392/python-class-static-methods) – 001 Apr 17 '18 at 04:26
  • 1
    @JohnnyMopp I'm not sure the OP is looking for a `staticmethod` because they are manipulating an instance variable created in `__init__()`. – AChampion Apr 17 '18 at 04:28
  • For more advice on how to write a good question, see: https://stackoverflow.com/help/how-to-ask – Geoffrey Wiseman Apr 17 '18 at 04:34

1 Answers1

3

There are two mistakes in your code. First, this:

def get_list(self):
    self.student_list

should be:

def get_list(self):
    return self.student_list

Second, you're using the class StudentRepo where you should be using an instance of StudentRepo:

s1 = Student("A", 10)
s2 = Student("B", 11)

my_roster = StudentRepo()

my_roster.add(s1)
my_roster.add(s2)

studentList = my_roster.get_list()
for student in studentList:
    print(student.name)
cdlane
  • 40,441
  • 5
  • 32
  • 81