In python ,how can I use a method of a class in a normal function outside the class?
Class Python:
def __init__(self,a):
self.__a=a
def get_a(self):
return self.__a
def normal_func:
var=Python.get_a()
print(var)
In python ,how can I use a method of a class in a normal function outside the class?
Class Python:
def __init__(self,a):
self.__a=a
def get_a(self):
return self.__a
def normal_func:
var=Python.get_a()
print(var)
The get_a() method presented in the question is an instance method. This means that all objects of the class Python can call the get_a() method. The easiest way to use the object methods of a class, in a function, is to create an object of the class and then carrying out any operations on it. So the code above will be re-factored to:
class Python:
def __init__(self,a):
self.__a=a
def get_a(self):
return self.__a
def normal_func:
P = Python('a')
var=P.get_a()
print(var)
If the normal_func is supposed to do perform differently for different values of <PythonObject>.a, I would suggest that you add the object as a parameter for the function. So the new function would be something like this:
def normal_func(PythonObject):
var = PythonObject.get_a()
print(var)