为什么不能在python中超级访问类中的属性? [英] Why can't super access the attribute in a class in python?
问题描述
我有个问题.在使用 python 的 oops 中, super 可以访问 method 或 constructor ,但不能访问 attributes .这是为什么??
i have a question. In oops using python, super can access the method or constructor , but not the attributes . Why is that??
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)
谁能解释一下??如果可能,那怎么做?
Can anyone please explain?? If possible then how?
推荐答案
首先我认为 - 这很明显.然后,这实际上是一个有趣的问题,我今天学到了一些新东西.
First I thought - it's obvious. And, then, it is actually an interesting question, and I learned something new today.
super() 不返回实例化的类对象.它返回一个super"类的实例,该类将类SmartPhone"和SmartPhone object"作为参数.然后它运行这个闭包.
super() doesn't return the instantiated class object. It returns an instance of "super" class that takes the class "SmartPhone" and "SmartPhone object" as arguments. It then runs this closure.
因此,您无法根据 super() 的值获取超类的属性,因为它是超"类的实例.
As such, you cannot get to the attributes of super class on the value of super() because it's an instance of "super" class.
https://docs.python.org/3.7/library/functions.html#super
这篇关于为什么不能在python中超级访问类中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!