簡體   English   中英

Python AttributeError:對象在Unittest中沒有屬性

[英]Python AttributeError: Object has no attribute in Unittest

我有 2 個腳本,第一個是 All_Methods,另一個是 All_Testcases,因為我使用的是 unittest 框架,所以我們開始吧。

All_Methods 就像:

class All_Services():
    def abc(self):
        x =1

    def bca(self):
        print "My Name is Taimoor"
        self.abc()

    def cba(self):
        self.bca()

在另一個腳本 All_TestCases 上是這樣的:

from All_Methods import All_Services as service

    class All_TestCases(unittest.TestCase):
        def test_1_running_method(self)
            service.cba(self)

異常顯示是:

AttributeError: 'All_TestCases' object has no attribute 'bca'

請有人告訴我,我在這里缺少什么? 謝謝。

當您將 self 傳遞給您在類上調用的方法時,您並沒有以通常的方式使用類。 常見的是在類的實例上調用方法並隱式獲取 self 參數。

當你調用Method.running_query_Athena(self)自我是一個實例All_TestCases不具備的方法connecting_Athena

您的意思是All_TestCases派生自All_Methods嗎?

為什么All_Methods是一個類?

  1. 使用適當的縮進,因為 python 完全基於代碼的縮進方式。
  2. 請,請使用正確的命名約定; 根據PEP 8 的建議。
  3. 您試圖在沒有實例的情況下訪問實例方法。

請嘗試以下操作:

class MyClass:
    def my_instance_method(self):
        return True

    @classmethod
    def my_class_method(cls):
        return True

    @staticmethod
    def my_static_method():
        return True

這行不通:

>> MyClass.my_instance_method()
TypeError: my_instance_method() missing 1 required positional argument: 'self'

但是這些會因為它們沒有綁定到正在創建的類實例。

MyClass.my_class_method()
MyClass.my_static_method()

實例方法要求您實例化類; 意思是你使用:

MyClass().my_instance_method()

由於您似乎想在類實例上設置response_id 使用表示類實例的self參數來獲取response_id - 建議你使用實例方法,如上圖實例化類(注意類名后面的()

請在問題中修復您的格式。

示例中的代碼有很多問題,但暫且不提。

該錯誤是由於將class A的實例作為self參數傳遞給class B的(非靜態)方法引起的。 Python 將嘗試在class A的實例上調用此方法,從而導致缺少屬性錯誤。

這是問題的一個簡化示例:

class A:
    def is_ham(self):
        # Python secretly does `self.is_ham()` here, 
        # because `self` is the current instance of Class A. 
        # Unless you explicitly pass `self` when calling the method.
        return True


class B:
    def is_it_ham(self):
        # Note, `self` is an instance of class B here.
        return A.is_ham(self)


spam = B()
spam.is_it_ham()

暫無
暫無

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

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