Reputation: 1
I am new to python and I'm trying to add math module inside my class but I don't know what is the right way adding it
import math
class myClass():
#some code
or
class myClass():
import math
#some code
What is the right way the first or the second one?
Upvotes: 0
Views: 284
Reputation: 106455
Anything declared inside a class definition becomes a class variable, a module included, so by importing math
within a class definition, it becomes a class variable that is accessible only via the class object or the instance object, so:
class myClass:
import math
def __init__(self, value):
self.value = value
def sqrt(self):
return math.sqrt(self.value)
print(myClass(4).sqrt())
would result in:
NameError: name 'math' is not defined
but changing the sqrt
method to:
def sqrt(self):
return self.math.sqrt(self.value)
would properly output:
2.0
That said, there is usually no good reasons to import modules as class variables. In the vast majority of cases modules are imported outside the class, as global variables.
Upvotes: 3