簡體   English   中英

如何使用 3 個函數調用 class?

[英]How to call on a class using 3 functions?

我想創建一個具有 3 個功能的 Python class。

  • Function 1 將要求用戶輸入一個數字。
  • Function 2 將要求用戶輸入另一個數字。
  • Function 3 將乘以 function 1 * function 2 並返回乘積。

這是我到目前為止的代碼:

class Product:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        x = int(input('What is the first number?: ')

    def get_y(self):
        y = int(input('What is the second number?: ')

    def mult_XY(self):
        return x * y  

當我嘗試調用 class 時,我得到'y' is not defined

我嘗試使用以下代碼:

num = Product(x, y)
print(num.mult_XY)

這是一個可行的解決方案。 將其與您當前的解決方案進行比較並找出差異。 在下面的代碼片段之后,我將突出顯示您需要研究的概念,以便更好地理解該程序。

這是您的代碼的正確版本(注意:可能有不止一種解決方案):

class Product:

    def __init__(self):
        return

    def get_x(self):
        self.x = int(input('What is the first number?: '))
        return self.x
    
    def get_y(self):
        self.y = int(input('What is the second number?: '))
        return self.y

    def mult_XY(self):
        return self.x * self.y

p = Product()
x = p.get_x()
y = p.get_y()
result = p.mult_XY()
print('RESULT of {} * {} = {}'.format(x, y, result))

這是最好的答案嗎? 不。根據您的程序的具體情況,代碼的結構可能會有所不同。

您在以下概念上存在知識差距:

  • Python中的對象和類
  • Python中的函數
  • Python 中的變量和作用域

為了更好地理解,您需要了解更多有關 Python 的基礎知識。這里有一個很好的入門資源: https://python-textbok.readthedocs.io/en/1.0/Introduction.html

讀完之后,您不僅可以回答這個問題,還可以為您的編程知識打下基礎。 不要放棄,祝你一切順利。

您似乎忘記在 function 定義中使用關鍵字self 您的代碼中有很多錯誤。 我認為這是您的代碼的正確版本:

class Product:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        self.x = int(input('What is the first number?: '))

    def get_y(self):
        self.y = int(input('What is the second number?: '))

    def mult_XY(self):
        return self.x * self.y

這就是您應該如何檢查它是否正常工作:

(更新后的版本)

x = 10
y = 5
num = Product(x, y)
num.get_x()
num.get_y()
print(num.mult_XY())

要引用存儲在當前 object 中的任何內容,您需要使用self. 就像您在 init function 中所做的那樣,最初保存值。

例子:

class Product:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        self.x = int(input('What is the first number?: '))

    def get_y(self):
        self.y = int(input('What is the second number?: '))

    def mult_XY(self):
        return self.x * self.y  

我不確定我是否理解正確,但您可能需要“x”和“y”作為 class 中的輸入。

如果是這樣,請使用classmethod

class Product:
    @classmethod
    def get_x(self):
        self.x = int(input('What is the first number?: '))
        return self
    @classmethod
    def get_y(self):
        self.y = int(input('What is the second number?: '))
        return self
    @classmethod
    def mult_XY(self):
        return self.x * self.y

前任:

>>> Product.get_x().get_y().mult_XY()
What is the first number?: 3
What is the second number?: 4
12
>>> 

暫無
暫無

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

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