![](/img/trans.png)
[英]AttributeError: 'GoogleSearch' object has no attribute 'driver' while executing tests through Python 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
是一个类?
请尝试以下操作:
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.