What is the main difference between class
and def
in python? Can a class in python interact with django UI (buttons)?
class is used to define a class (a template from which you can instantiate objects). def is used to define a function or a method. A method is like a function that belongs to a class.
Functions do specific things, classes are specific things. Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.
Classes are like a blueprint or a prototype that you can define to use to create objects. We define classes by using the class keyword, similar to how we define functions by using the def keyword.
One key distinction between functions and classes was highlighted in this talk which suggests that a function is a behavior that can carry data while, inversely, a class is data that can carry behavior.
class
is used to define a class (a template from which you can instantiate objects).
def
is used to define a function or a method. A method is like a function that belongs to a class.
# function
def double(x):
return x * 2
# class
class MyClass(object):
# method
def myMethod(self):
print ("Hello, World")
myObject = MyClass()
myObject.myMethod() # will print "Hello, World"
print(double(5)) # will print 10
No idea about the Django part of your question sorry. Perhaps it should be a separate question?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With