我有两个脚本,第一个是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'好心的人告诉我,我在这里错过了什么?谢谢。
发布于 2018-10-15 19:28:39
当您将self传递给在类上调用的方法时,您将不会以通常的方式使用类。常见的是在类的实例上调用方法,并隐式地获取self参数。
当你调用Method.running_query_Athena(self)时,self是一个没有connecting_Athena方法的All_TestCases实例。
您的意思是让All_TestCases从All_Methods派生吗
为什么All_Methods是一个类呢?
发布于 2018-10-15 19:30:30
尝试以下操作:
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()实例方法需要实例化Class;这意味着您要使用:
MyClass().my_instance_method()因为您似乎想要在类实例上设置response_id;使用self参数来获取response_id。-我建议你使用一个实例方法来实例化这个类,如下所示(注意类名后面的() )
请修改您在问题中的格式。
发布于 2019-08-04 20:21:29
示例中的代码中有相当多的错误,但将其放在一边。
该错误是由于将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()https://stackoverflow.com/questions/52815621
复制相似问题