简体   繁体   中英

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

    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)?

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.

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.

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. 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. The n import that file and use the add function the way you are doing in your code.

#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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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