16

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

Martin
  • 3,396
  • 5
  • 41
  • 67
Slow learner
  • 171
  • 1
  • 1
  • 7
  • 3
    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](http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/) 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 Sep 18 '13 at 08:43
  • 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 Sep 18 '13 at 08:43
  • 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 Nov 16 '14 at 14:15

2 Answers2

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?

Adi Bnaya
  • 473
  • 4
  • 14
nakedfanatic
  • 3,108
  • 2
  • 28
  • 33
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
Aesthete
  • 18,622
  • 6
  • 36
  • 45