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.
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)
...
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
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!
Call a function inside a class when calling the class in python
You misunderstand how classes work. You put your call inside the class definition body; there is no instance at that time, there is no self
.
Call the method on the instance:
instance = printclass()
instance.dotheprint()
Now the dotheprint()
method is bound, there is an instance for self
to refer to.
If you need dotheprint()
to be called when you create an instance, give the class an __init__
method. This method (the initializer) is called whenever you create an instance:
class printclass():
string="yes"
def __init__(self):
self.dotheprint()
def dotheprint(self):
print self.string
printclass()
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"))
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).
Calling a function from a class without object
gemiddelde
is an instance method. To call it, you need an instance:
print(student1.gemiddelde())
Instance methods are the most common type of methods in Python classes. These are so called because they can access unique data of their instance.
Here, gemiddelde
needs access to the cijfers
attribute.
Take a look at the documentation about Classes.
Related Topics
Pandas: Sum Dataframe Rows for Given Columns
Printing Simple Diamond Pattern in Python
Python Pip Install Error [Ssl: Certificate_Verify_Failed]
Element That Appear More That Once in the List in Python
Get First Date and Last Date of Current Quarter in Python
How to Tell If Tensorflow Is Using Gpu Acceleration from Inside Python Shell
How to Display a Float With Two Decimal Places
Fill With Nan When Length of Values Does Not Match Length of Index
Check Type: How to Check If Something Is a Rdd or a Dataframe
Testing Whether a String Has Repeated Characters
Python: How to Calculate the Average Word Length in a Sentence Using the .Split Command
How to Read Image Data from a Url in Python
How to Limit Iterations of a Loop in Python
Pandas: Calculate the Percentage Between Two Rows and Add the Value as a Column
Extract File Name from Read_Csv - Python
Pandas - Find Index of Value Anywhere in Dataframe