Search code examples
pythoninheritancesubclasssuperclass

How can I access superclass attributes through the object externally?


class Student:
    name = "abc"

class Highschool(Student):
    name = "xyz"
    def t(self):
        print(super().name)    # I don't know why this also prints None.

a = Highschool()
print(a.name)              # Prints xyz
print(a.t())               # Prints abc.
print(a.super().name)      # Error

My question is, how can I get the last line to print abc without using the t() method.


Solution

  • You should be able to just do Student.name. If you needed to get it programmatically based on the instance a you could do:

    >>> a.__class__.__bases__[0].name
    'abc'
    

    since a.__class__ is Highschool, and Highschool.__bases__ is a sequence containing Student.

    Note that name is a class variable, not an instance variable -- one name is shared by all Students. This probably does not make a lot of sense for a Student class, nor does it make sense for a Highschool to itself be a type of Student.