为什么super无法访问python中类中的属性?

Ted*_*989 5 oop super python-3.x

我有个问题。在使用 python 的 oops 中, super 可以访问方法或构造函数,但不能访问属性。这是为什么??

class Phone:

  def __init__(self, price, brand, camera):
    print ("Inside phone constructor")
    self.__price = price
    self.brand = brand
    self.camera = camera

def buy(self):
    print ("Buying a phone")

def return_phone(self):
    print ("Returning a phone")

class FeaturePhone(Phone):
    pass

class SmartPhone(Phone):
    def __init__(self, price, brand, camera, os, ram):
       super().__init__(price, brand, camera)
       self.os = os
      self.ram = ram
      print ("Inside smartphone constructor")

    def buy(self):
      print(super().camera) #Error
      print ("Buying a smartphone")

s=SmartPhone(20000, "Samsung", 12, "Android", 2)

print(s.buy()) #error
print(s.brand)
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下吗?如果可以的话怎么办?

小智 3

首先我想——这很明显。然后,这实际上是一个有趣的问题,我今天学到了一些新东西。

super() 不返回实例化的类对象。它返回“超级”类的实例,该类将类“SmartPhone”和“SmartPhone 对象”作为参数。然后它运行这个闭包。

因此,您无法通过 super() 的值获取超类的属性,因为它是“超级”类的实例。

https://docs.python.org/3.7/library/functions.html#super