0

So I understand that classes are basically blueprints for when you are coding, but the thing I don't understand is the difference they have from functions. Since for both of them you can assign variables and use different variables inside of them. And in order for both of them to work you have to use exampleclass() or examplefunction() for it to execute. Also as well you can execute a function inside a function or define a function within a functions and with a class you can execute or define a class inside a class.

example class:

class bank(object):
    def __init__(self, acc_num, acc_name, acc_DOB):
        self.acc_num = acc_num
        self.acc_name = acc_name
        self.acc_DOB = acc_DOB

or example function:

def bank(num, name, DOB):
    acc_num = num
    acc_name = name
    acc_DOB = DOB

*The two example I have given may not be perfectly correct but I was doing off the top of my head.

The two examples I have given look exactly the same but and look like they do the same thing so what is the difference.

5
  • 1
    What do you think b would be after running b = bank(1, 'bob', '1980-05-04') with the class, or with the function? Can you do anything useful with the function? Commented Nov 9, 2021 at 10:50
  • (Also, __init___ has too many underscores.) Commented Nov 9, 2021 at 10:50
  • Its just an example, its not an actual piece of code I'm just confused in why you would use a class and not just a function, @user2357112supportsMonica Commented Nov 9, 2021 at 10:52
  • Don't they basically do the same thing @user2357112supportsMonica, just that with a function it would take more code and be longer to express the same thing as with the class. Since with the function you can retrieve data from outside the function to use inside it like with the DOB and name and acc num. Commented Nov 9, 2021 at 10:54
  • 1
    you will find a good answer here: stackoverflow.com/questions/18202818/classes-vs-functions Commented Nov 9, 2021 at 10:57

1 Answer 1

1

Functions do specific things, classes are specific things.

Classes are a blueprint, like you said. A class can have methods inside of them, and in your example, you are showing the constructor in action. That method, when executed, creates a new object using that blueprint. Compared to the function you listed in your example, which creates local variables and sets them equal to the passed in parameters. Also, you can't "execute" a class. You can only call methods in it. Ex) class.method() compared to function().

Classes vs. Functions

Sign up to request clarification or add additional context in comments.

1 Comment

Alright that is really helpful and I think that answers my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.