Hamza Marie
Hamza Marie

Reputation: 21

OOP Python Problems

I learned Object Oriented Programming recently and I have these Problems when I make run for this code , I have this error How Can I Fix it ?

class Grade:
    def __init__(self,**kwargs):
        self.information = kwargs
    def grade(self):
        g = self.information['grade']
        print(g , "Grade")
    def students(self):
        s = self.information['students']
        print("students : ",s)
    def chairs(self):
        c = self.information['chairs']
        print("Chairs : ",c)
class school(Grade):
    def __init__(self,**kwargs):
        self._grades = kwargs
    def classes(self):
        print("YOU HAVE IN THE SCHOLL ",self._grades["classes"],"classes")  
    def students(self):
        super().students()   
first = Grade(grade="first" , students=20,chairs=15)
fir_g = school(classes=9)
fir_g.students()
    

Error:

Traceback (most recent call last):
  File "c:\Users\hp\Desktop\python\OOP.py", line 27, in <module>
    fir_g.students()
  File "c:\Users\hp\Desktop\python\OOP.py", line 19, in students
    super(school,self).students()
  File "c:\Users\hp\Desktop\python\OOP.py", line 8, in students
    s = self.information['students']
AttributeError: 'school' object has no attribute 'information'

How can Fix this problem ?

Upvotes: 0

Views: 190

Answers (1)

Rolv Apneseth
Rolv Apneseth

Reputation: 2118

I believe you just need to run the __init__ for the inherited class, as that's where you define information:

class school(Grade):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self._grades = kwargs

And that should then have information defined. It's important to always run the inherited class's __init__ method as it's not run automatically.

Note that this means you'll need to pass any arguments for Grade into school as well though. Although, it seems this isn't the structure you would want. Surely school would be above grades, so why have it inherit from Grade? I strongly suggest you rethink the structure of your classes and how you want them to interact with each other. Maybe you want a method in school where you can add a Grade object, or something like that.

Upvotes: 1

Related Questions