简体   繁体   English

python 调用类和函数

[英]python calling on classes and functions

i am trying to replicate something like the random.radient() function where you can do something like x = random.radient(1, 10) where the value gets stored in the x for example我正在尝试复制诸如 random.radient() function 之类的东西,您可以在其中执行诸如 x = random.radient(1, 10) 之类的操作,其中值存储在 x 例如

    file one
    
    class math:
    
        def add(self, nunber1, number2):
            self.nunber1 = nunber1
            self.number2 = number2
            return self.add(int(number1) + int(number2)) 
    
    
    file two
    
    import fileone

x = math.add(1, 2)
print(x)

so what do i add to the code in order for me to do the x = math.add(1, 2)?那么为了让我执行 x = math.add(1, 2),我应该在代码中添加什么?

File one should be like this文件一应该是这样的

from test import *
x = math.add(1, 2)
print(x)

because otherwise, you don't actually import the class.因为否则,您实际上不会导入 class。

File two should be文件二应该是

class math:
    
    def add(number1, number2):
        number1 = nunber1
        number2 = number2
        return (int(number1) + int(number2)) 

Because you are giving the function the variable you do not need to give itself that will just result in an error.因为你给 function 变量你不需要给自己,这只会导致错误。

As well as that you used the add function while returning, which will only give you an error because you're giving it one variable instead of two.以及您在返回时使用了 add function ,这只会给您一个错误,因为您给它一个变量而不是两个。 Im not sure why you did it that way but it is unnecessary to try and use recursion while adding.我不确定你为什么这样做,但在添加时没有必要尝试使用递归。

The simplest way to archive what you want is to create a file called math.py, create the add function direct in the file.归档你想要的最简单的方法是创建一个名为 math.py 的文件,在文件中直接创建 add function。 The n import that file and use the add function the way you are doing in your code. n 导入该文件并按照您在代码中执行的方式使用添加 function。

#math.py #math.py

def add(self, nunber1, number2):
    self.nunber1 = nunber1
    self.number2 = number2
    return self.add(int(number1) + int(number2))

#test.py import math x = math.add(1, 2) print(x) #test.py 导入数学 x = math.add(1, 2) print(x)

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

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