如何从外部通过对象访问超类属性?

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

我的问题是,如何在不使用 t() 方法的情况下获取最后一行来打印 abc。

你应该可以做到 Student.name。如果您需要根据实例 a 以编程方式获取它,您可以这样做:

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

因为a.__class__Highschool,而Highschool.__bases__是一个包含Student.

的序列

请注意 name 是一个 class 变量,而不是实例变量 -- 一个 name 由所有 Student 共享。这对于 Student class 可能没有多大意义,对于 Highschool 本身是一种 Student.[=23= 也没有意义]

您可以创建基础 class 对象

    b = Student()
    print(b.name)