Not fully understanding why some things about classes, such as why I have to set self.variable = variable (don’t understand why it’s not just automatically being set when im setting all the objects in the init method). Right now the biggest thing I confuse myself on is I’ve always called functions to use by doing:
method(variable)
But now when calling a method from a class it’s:
self.method()
I’m not fully understanding why the prior doesn’t work in this scenario, maybe I’m looking over something really basic here, hoping someone can enlighten me.
No, they are both functions. A method has a context (self, the instance), whereas a function does not. A function can operate in any environment.
Consider the built-in function, len(). It can be used on all sorts of objects, strings, lists, dictionaries, tuples and sets. It does not belong to any one class.
Now consider the string method, str.lower(). The dot tells us that .lower() is a method of the str class. We cannot use the method on any other type of objects because they are not instances of the str class.
if inside your class you had a method called my_name looking something like this:
def my_name(self, name):
print "my name is %s" % (name)
It still doesn’t fully click why you couldn’t do my_name(foo) instead of foo.my_name() but I’ll probably understand more with experience.
I think I might understand to some extent though; foo.my_name() works because you’re calling it from a class, whereas my_name(foo) would only work if the function was written outside of a class.