簡體   English   中英

Python / PyCharm缺少參數'self'?

[英]Python / PyCharm missing argument 'self'?

我目前正在學習Python,我不明白我的代碼有什么問題,但PyCharm一直給我以下錯誤:

Traceback (most recent call last):
File "C:/Users/Sam/PycharmProjects/untitled1/app.py", line 5, in <module>
    fish1.bubbles()
TypeError: bubbles() missing 1 required positional argument: 'self'

這是我的代碼:

import random
from Fish import Fish

fish1 = Fish
fish1.bubbles()

fish1.name = input("enter the name of your fish: ")
fish1.coords = ("({0},{1})".format(random.randint(1, 100), random.randint(1, 100)))

print("The fish's name is {0}, and it is swimming at co-ordinates{1}".format(fish1.name, fish1.coords))

這是我的Fish.py文件:

class Fish:

    def __init__(self, name, coords):
        self.name = name
        self.coords = coords

    def bubbles(self):
        print("{0} blew some bubbles".format(self))

任何幫助,將不勝感激!

你需要調用的構造函數 的類 來創建的實例

fish1 = Fish()

在你的情況下,它將與參數

fish = Fish("fish_name", "coordinates")

Fish是班級。 你不能要求抽象的魚來制造泡泡。 你必須問一個特定的魚(即該類的一個對象 )。 所以,假設你的魚是“bob”

bob = Fish()
bob.bubbles()

您在創建實例對象時遇到錯誤

在本節中, fish1 = Fish您沒有創建實例,但嘗試使用fish1.bubbles()

所以嘗試改變fish1 = Fish to fish1 = Fish(name, coords)

構造函數中需要的namecoords

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM