简体   繁体   English

通过将类作为该函数的参数传递来访问“另一个python文件的函数”中的“类的方法”

[英]Access "a method of a class" in "a function of another python file" by passing the class as that function's parameter

I have a class file.我有一个类文件。 Let's call it "C1.py".我们称之为“C1.py”。 The sample code looks like below.示例代码如下所示。

class C1(object):

    def __init__(self):
        self.greeting = "Hello, world!"

    def M1(ans):
        if ans == 1 or ans == 2:
            return True
        else:
            return False

Now, I have another python file in the same folder, which will access the class file shown above.现在,我在同一个文件夹中有另一个 python 文件,它将访问上面显示的类文件。

from trial import C1

def getAns(class1):
    while True:
        ans = input("Answer: ")
        if class1.M1(ans):
            return ans
            break

sample = C1()
print sample.greeting
ans = getAns(sample)
print ans

When I run those files, sample.greeting prints fine.当我运行这些文件时,sample.greeting 打印得很好。 Everything is fine until when the execution reaches the line "ans = getAns(C1)", which gives the error "M1() takes exactly 1 argument (2 given)".一切都很好,直到执行到达“ans = getAns(C1)”这一行,这给出了错误“M1() 只需要 1 个参数(给定 2 个)”。

So, where in the code should I change so that I can call that method successfully?那么,我应该更改代码中的哪个位置才能成功调用该方法?

Note here that the above code is only the abstraction of my whole program to highlight my problem.这里注意,上面的代码只是我整个程序的抽象,以突出我的问题。 It sounds stupid with just the code above alone.仅使用上面的代码听起来很愚蠢。 So, please, please bear with that for me.所以,拜托,请为我忍受。

M1 is currently defined as a method of C1, as such it needs to have an additional self argument which would be the instance of the class. M1 目前被定义为 C1 的一个方法,因此它需要有一个额外的 self 参数,这将是类的实例。 Ie IE

class C1(object):

    def __init__(self):
        self.greeting = "Hello, world!"

    def M1(self, ans):
        if ans == 1 or ans == 2:
            return True
        else:
            return False

In other languages such as C++ or Java the presence of self (or this) is implicit, but in python it's explicit.在 C++ 或 Java 等其他语言中,self(或 this)的存在是隐式的,但在 python 中是显式的。

alternatively if you don't want or need M1 to access C1's state you could make M1 static via @staticmethod ie或者,如果您不想或不需要 M1 来访问 C1 的状态,您可以通过 @staticmethod 即使 M1 为静态

class C1(object):

    def __init__(self):
        self.greeting = "Hello, world!"

    @staticmethod
    def M1(ans):
        if ans == 1 or ans == 2:
            return True
        else:
            return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM