Home > Back-end >  python calling on classes and functions
python calling on classes and functions

Time:12-04

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

CodePudding user response:

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.

CodePudding user response:

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)

  • Related