簡體   English   中英

類變量-缺少一個必需的位置參數

[英]Class variables - missing one required positional argument

我有兩個腳本。 第一個包含一個類,其中定義了類變量,以及使用這些類變量的函數。 第二個腳本在其自身的函數內調用類和函數。

這種設置對於類中的函數來說效果很好,但是添加類變量會導致以下錯誤。 誰能解釋為什么,請以及我需要做什么來解決?

謝謝

obj1.py:

class my_test_class():

    def __init__(self):

        self.test1 = 'test1'
        self.test2 = 'test2'
        self.test3 = 'test3'

    def test_func(self, var):

        new_var = print(var, self.test1, self.test2, self.test3)

obj2.py

from obj1 import *


def import_test():

    target_var = my_test_class.test_func('my test is:')
    print(target_var)

import_test()

錯誤:

Traceback (most recent call last):
  File "G:/Python27/Test/obj2.py", line 9, in <module>
    import_test()
  File "G:/Python27/Test/obj2.py", line 6, in import_test
    target_var = my_test_class.test_func('my test is:')
TypeError: test_func() missing 1 required positional argument: 'var'

正如評論者所指出的那樣,由於test_func是類方法,因此我們需要使用類實例對象來調用它。

另外print函數返回None,因此執行new_var = print(var, self.test1, self.test2, self.test3)會分配new_var=None ,因此,如果要返回變量,則需要分配new_var = ' '.join([var, self.test1, self.test2, self.test3]) ,創建一個在所有單詞之間帶有空格的字符串,並return new_var

結合所有這些,代碼如下

class my_test_class():

    def __init__(self):

        self.test1 = 'test1'
        self.test2 = 'test2'
        self.test3 = 'test3'

    def test_func(self, var):

        #Assign value to new_var and return it
        new_var = ' '.join([var, self.test1, self.test2, self.test3])
        return new_var

def import_test():

    #Create instance of my_test_class
    test_class = my_test_class()
    #Call test_func using instance of my_test_class
    print(test_class.test_func('my test is:'))

import_test()

my test is: test1 test2 test3輸出將my test is: test1 test2 test3

暫無
暫無

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

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