How to Call a Function Within a Class

How can I call a function within a class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
self.distToPoint(p)
...

calling a method inside a class-Python

You haven't created an object to the above class.

Any function/method inside a class can only be accessed by an object of that class .For more information on the fundamentals of Object Oriented Programming, please check this page.

Meanwhile for this to work, define your class in the following way :

class Time:

def __init__(self,x=None,y=None,z=None):
self.hour=x
self.minute=y
self.second=z

def __str__(self):
return "({:02d}:{:02d}:{:02d})".format(self.hour, self.minute, self.second)

def time_to_int(time):
minutes=time.hour*60+time.minute
seconds=minutes*60+time.second
return seconds

def int_to_time(seconds):
time=Time()
minutes,time.second=divmod(seconds,60)
time.hour,time.minute=divmod(minutes,60)
return time

def add_time(t1,t2):
seconds=time_to_int(t1)+time_to_int(t2)
return int_to_time(seconds)

and outside the class block, write the following lines :

TimeObject = Time()
start=Time(9,45,00)
running=Time(1,35,00)
TimeObject.add_time(start,running)
print "done"

I however suggest you to write the add_time function outside the class because you are passing the objects to the class as the parameters to the function within the same class and it is considered as a bad design in object oriented programming.
Hope it helps. Cheers!

Defining and Calling a Function within a Python Class

Define and call plus_2_times_4 with self, namely:

class ExampleClass():

def __init__(self, number):
self.number = number

def plus_2_times_4(self,x):
return(4*(x + 2))

def arithmetic(self):
return(self.plus_2_times_4(self.number))

This will work.

Python calling a function from another function in a class

You forgot to put the self in the method signature of main(). It should look like this

    def main(self):
self.square(3)

Without that, self is in fact not defined in the scope of your method, so Python complains.

EDIT: also, as Some programmer dude mentions, your code never creates an instance of the class just executes main. There's also a problem with your indentation (probably a copy-paste error).

Try this instead:

class Back(object):    
def square(self,x):
y = x * x
return y

def main():
back = Back()
print(back.square(3))


if __name__ == "__main__":
main()

notice how main is defined at the root level (it's not indented like square). It's not part of the class this way and doesn't need self. You could make it a method of the Back class again like this:

class Back(object):    
def square(self,x):
y = x * x
return y

def main(self):
print(self.square(3))


if __name__ == "__main__":
back = Back()
back.main()

Ok, this last one, it doesn't really make sens to do it this way, I admit. But I'm just trying to illustrate scope and the difference between function and methods in python (I think this logic may help the OP more, considering the question).

How can I call a function inside a class?

First you should have init function in a class to call the class, then you should create some functions. Then you can create some static function that can be called without passing the parameters of the Class.
In Your globals.py file:

class Fg:
def __init__(self):
#You can place some code that you
#want to call when this class is called
self.text = ""

def red(self, text):
#The self.text will make the text usable by
# both the functions
self.text = text

#Return what ever you want
return f'\033[00;49;031m{text}\033[0m'

def heading(self, text):
self.text = text
return self.red()

In your testrun.py file:

from globals import Fg

print(Fg().red("Your Text"))
print(Fg().heighlight("Your Text"))

Call a function inside of a function inside of a class in Python

Updated after question edit:

Check out this link that shows how to make a "closure" https://stackoverflow.com/a/4831750/2459730

It's what you described as a function inside of a function.

def run(self):
def calculate(self): # <------ Need to declare the function before calling
return self.number**2

print "I will now square your number"
print "Your number squared is: "
print self.calculate() # <---- Call after the function is declared

Before question edit:
Your calculate function isn't indented properly.

def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()

#This squares the number
def calculate(self): # <----- Proper indentation
return self.number**2 # <------ Proper indentation

The calculate function should have the same indentation level as the run function.

Using a function within a class in python (to use self or not)

sigmoid is a method of the Neuralnetwork class, so you need to create an instance of the Neuralnetwork class first, before you can utilize the sigmoid function, if you're calling it after the class definition:

class Neuralnetwork(object):
def __init__(self, data):
self.data = data

def scan(self):
print(self.data)

def sigmoid(self, z):
g = 1 / (1 + math.exp(-z))
return (g)

# replace data and z with appropriate values
nn = Neuralnetwork(data)
a1 = nn.sigmoid(z)
print a1

If you need to use it within the class, put the block within a method:

class Neuralnetwork(object):
def __init__(self, data):
self.data = data

def scan(self):
print(self.data)

def sigmoid(self, z):
g = 1 / (1 + math.exp(-z))
return (g)

def print_sigmoid(self, z):
a1 = self.sigmoid(z)
print a1

# replace data and z with appropriate values
nn = Neuralnetwork(data)
nn.print_sigmoid(z)

I also recommend changing the class name to NeuralNetwork, as per the PEP 8 Style Guide: https://www.python.org/dev/peps/pep-0008/#class-names

How to call a function from an object within a class?

There is nothing stopping you from storing functions in a dictionary for lookup. Here is an example that shows the correct syntax.

class foo:
def __init__(self, items):
self.myObj = {
"item one": self.functionOne,
"item two": self.functionTwo
}
self.__handler(items)
def __handler(self,items):
for item in items:
if item in self.myObj.keys():
self.myObj[item]()
def functionOne(self):
print("bar")
def functionTwo(self):
print("baz")

foo(["item one"])
foo(["item two","item one"])

prints:

bar
baz
bar


Related Topics



Leave a reply



Submit