[Fixed]-Differences between `class` and `def`

23👍

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?

6👍

class defines a class.

def defines a function.

class Foo:
    def Bar(self):
        pass

def Baz():
   pass

f = Foo() # Making an instance of a class.
f.Bar() # Calling a method (function) of that class.
Baz() # calling a free function

Leave a comment