【问题标题】:Why can't super access the attribute in a class in python?python 为什么不能超级访问类中的属性?
【发布时间】:2019-11-15 16:17:56
【问题描述】:

我有一个问题。在使用 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)

谁能解释一下??如果可以的话怎么做?

【问题讨论】:

    标签: python-3.x oop super


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 您好 Naoyuki Tai,我知道调用部分和接受参数。但是如果它返回超类的实例,则意味着它返回电话类对象。所以它应该可以像普通对象一样访问电话类的属性。
    • 如果你真的想访问这个值,(a) 你可以使用普通的 "self.FOO" (b) 你可以通过调用函数 super().__getitem__() 来实现。请阅读rhettinger.wordpress.com/2011/05/26/super-considered-super
    【解决方案2】:

    您不必访问父类即可使用其中一种方法。您的类-SmartPhone 继承自 Phone 类,它允许您使用 self 访问其属性和方法。所以你只需要调用self.buy()就可以使用该方法

    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(self.camera) 
          print ("Buying a smartphone")
    
    s=SmartPhone(20000, "Samsung", 12, "Android", 2)
    
    print(s.buy()) # this works
    print(s.brand)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多