為什么python類的函數被調用兩次[關閉](Why a function of python class is called twice [closed])
我遇到了兩次調用的python類函數的問題。 我正在使用Spyder IDE。
這是我的簡單代碼
class Test:
def f(self):
print("a")
from Test import *
t = Test()
t.f()
當我按“運行文件”按鈕...結果是
a
a
但當我嘗試突出顯示所有內容并按“運行單元格”時...結果是
a
我想知道當我按“運行文件”時會發生什么,以及如何解決這個問題。
非常感謝
I am having a problem with the function of python class that is called twice. I am using Spyder IDE.
Here is my simple code
class Test:
def f(self):
print("a")
from Test import *
t = Test()
t.f()
When I press "Run File" button...the result is
a
a
But when I try to highlight everything and press "Run Cell"...the result is
a
I would like to know what happen when I press "Run File" and how to solve this issue.
Many thanks
原文:https://stackoverflow.com/questions/42620635
2020-02-19 17:30
滿意答案
因為你應該導入模塊 ,而不是類。 因此,當您from Test import *執行操作時from Test import *您正在運行所有代碼,其中包括實例化和調用f方法。 導入后,你實例化并再次調用它,這就是它被打印兩次的原因,因為它正在運行兩次。
Because you should import modules, not classes. So when you are doing from Test import * you are running all your code, which includes the instantiation and call to the f method. And after importing you are instantiating and calling it again, so that's the reason it is being printed twice, because it is being run twice.
2017-03-06
相關問答
這可能不直接回答你的問題,但一定會有幫助。 如果使用具有選項--sort累積的分析器,它將按累積時間對功能進行排序。 這有助于檢測不僅重要的功能,而且檢測它們的功能。 python -m cProfile --sort cumulative myScript.py
有一個解決方法來獲取調用者的功能: import inspect
print inspect.getframeinfo(inspect.currentframe().f_back)[2]
您可以添加任意數量的f_back,以防您想要...
您的代碼段中未調用此函數兩次。 我假設我們還沒有看到更多的代碼,它們調用myFunction ; 然后,調用該函數兩次的目的是顯示排序函數的效果。 假設在顯示函數之后調用myFunction ,程序將執行以下操作: 以他們開始的(未分類)順序顯示汽車 運行myFunction對汽車進行排序,然后再次顯示它們 這將允許用戶在排序之前和之后查看汽車列表之間的差異。 The function is not called twice in your snippet. I'm assuming there'...
class information:
def __init__(self, name, age, gender, enlistmentNum):
self.name = name
self.age = age
self.gender = gender
self.enlistmentNum = enlistmentNum
self.playerinf()
在init函數結束時調用playerinf。 在實例化...
對于你的例子, a = b.method(c); ,除了復制省略外,可能會有三份副本。 第一種是將c對象復制到函數參數x 。 第二個是從函數返回x對象的時候。 第三種是將返回值復制到對象中。 前兩個涉及復制構造函數,最后一個涉及復制賦值運算符,除非您將其更改為Student a = b.method(c); ,在這種情況下,他們都使用復制構造函數。 a , b和c都將在其范圍的末尾被銷毀。 對象x將在method函數的末尾被銷毀。 函數的返回值將在包含它的完整表達式的末尾被銷毀 - 也就是說,一旦...
在我看來,如果您在測試時編寫函數以不同的方式運行,那么您并沒有真正測試它。 為了測試函數,我會mock.patch()數據庫對象,然后檢查它在函數中是否正確使用。 開始使用模擬庫時最困難的事情是找到要替換的正確對象 。 在您的示例中,如果在your_module從Database_IO模塊導入Database_read對象,則可以使用類似于以下內容的代碼對其進行測試 with mock.patch('your_module.Database_read') as dbread_mock:
#...