14
votes

What is the main difference between class and def in python? Can a class in python interact with django UI (buttons)?

2
It may not seem like it, but there's actually a tremendous difference between the two. They're both techniques used to help organize code, but there are loads of differences in what they do, how they're used, and why you would use them. The topic is really too huge to easily cover in a single answer. Here's an introduction to classes/objects that you could try reading. Once you kind of understand the broad concepts, feel free to come back and ask more questions if you're still confused. - Michael0x2a
I suggest you look up object-oriented programming on wikipedia or so, to understand what a class is. To access a 'def' from within a class, you need to first make an object of that class, and than do object.nameofdef(), which than executes that 'def' on the object, while if you just make a 'def' outside of a class, it can be executed on whatever you want, but without it being linked to a certain object (not sure if this is explaining a lot, but i dont know how to be clearer on this) - usethedeathstar
Classes are a way of organization functions. If you want to a call a function, you have to first mention the class followed by the dot e.g. class.function. Now when we talk about objects, what we mean is that we create a object x for example by assigned x to a class e.g. x = class and in this way we can simpley invoke class.function by writing instead x.function. x is an object because it now contains functions as opposed to being a variable and containing only numbers for example. - the_prole

2 Answers

18
votes

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?

4
votes

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