亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Square 子類的 __init()__ 函數中使用 super() 時,Square 對象具有

Square 子類的 __init()__ 函數中使用 super() 時,Square 對象具有

慕桂英546537 2024-01-04 09:50:23
請考慮以下代碼:class Rectangle(object):    def __init__(self, height, length):        self.height = height        self.length = length        def area(self):        return self.height * self.length        def perimeter(self):        return 2 * (self.height + self.length)class Square(Rectangle):    def __init__(self, length):        super(Square, self).__init__(length, length)s = Square(5)s.area(), s.perimeter()對象包含哪些屬性Square——它只是length屬性還是兩者height兼而有之length?__init__()如果我們看到類方法的參數Square,它必須只包含length屬性。但super()方法正在初始化length和height屬性。一個人應該如何想象一個Square物體?
查看完整描述

2 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

print(s.__dict__)

給出{'height': 5, 'length': 5}


所以,它具有這兩個屬性。


附加信息:- 為了清楚起見,您還可以help在實例上使用。對于例如


print(help(s))  That will give:


Help on Square in module __main__ object:


    class Square(Rectangle)

     |  Square(length)

     |  

     |  Method resolution order:

     |      Square

     |      Rectangle

     |      builtins.object

     |  

     |  Methods defined here:

     |  

     |  __init__(self, length)

     |      Initialize self.  See help(type(self)) for accurate signature.

     |  

     |  ----------------------------------------------------------------------

     |  Methods inherited from Rectangle:

     |  

     |  area(self)

     |  

     |  perimeter(self)

     |  

     |  ----------------------------------------------------------------------

     |  Data descriptors inherited from Rectangle:

     |  

     |  __dict__

     |      dictionary for instance variables (if defined)

     |  

     |  __weakref__

     |      list of weak references to the object (if defined)


查看完整回答
反對 回復 2024-01-04
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

正方形物體將具有高度和長度。

Square 的構造函數僅接受長度,但這并不意味著 Square 可以擁有的唯一屬性就是長度。當我們調用超類的構造函數時,它有兩個高度和長度輸入,兩者僅傳遞長度。在父構造函數中,高度和長度設置為 length,這導致 Square 具有這兩個屬性。


查看完整回答
反對 回復 2024-01-04
  • 2 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號