iT邦幫忙

1

python class 問題

JK 2018-10-07 16:51:011238 瀏覽
  • 分享至 

  • twitterImage
class first():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def animal(self, color):
        self.color=color
pig=animal("red")
print(pig.color)

為什麼這樣寫有錯誤

神Q超人 iT邦研究生 5 級 ‧ 2018-10-07 17:32:34 檢舉
因為類別是first,他會建立一個物件,
而animal是物件中的屬性,
如果要使用的話先透過first把物件建立出來後
再從該物件去執行animal
神Q超人 iT邦研究生 5 級 ‧ 2018-10-07 17:37:04 檢舉
把最下面兩行改成這樣子試試:
#藉由class產生物件
pig=first("name",20)
#印出物件的屬性name和age
print(pig.name)
print(pig.age)
#由物件方法增加屬性color
color = pig.animal("red")
#印出屬性值
print(pig.color)
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
黃彥儒
iT邦高手 1 級 ‧ 2018-10-07 18:41:56
class first():
    def __init__(self, name, age):
        self.name = name
        self.age = age

class animal(first):
    def __init__(self, coler, name=None, age=None)
        super().__init__(name, age)
        self.coler = coler

pig=animal("red")
print(pig.color)

我要發表回答

立即登入回答