0

If I have a function called 'classic' I would normally define it like so:

def classic(x,y):
    return(x + y)

I can pass things through the function by using the parameters, such as:

classic(1,2)

If I have a method, the code would be something like:

class MyClass:
    # member variables
    variable1 = something
    variable2 = something_else

    # member functions
    def function1(self, parameter1):
        self.variable1 = variable1
        # defining a new variable 
        self.variable3 = something_more

Questions:

  • How does variable1 get passed through the method? Is variable1 actually parameter1 or is self doing something to variable1?

  • Why is self.variable3 = something_more used instead of variable3 = something_more?

Charles Duffy
  • 257,635
  • 38
  • 339
  • 400
Happle
  • 1
  • I believe the author of the answer at https://stackoverflow.com/a/43921843/14122 was working through the same issues you're asking about here -- perhaps their answer will be helpful. Note in particular what they're talking about wrt. an instance variable (or local) shadowing, *but not changing*, your class variable. – Charles Duffy Jul 16 '18 at 00:19
  • You can actually experiment with this yourself -- if you just run `variable3 = something_more` without the `self.`, it'll no longer have the same value next time a function is called on the same object, because what you're assigning is local. – Charles Duffy Jul 16 '18 at 00:21
  • 'Variables created inside __init__ (and all other method functions) and prefaced with self. belong to the object instance. ' I though the entire class was an instance of an object – Happle Jul 16 '18 at 00:30
  • @Happle: The class is (under 3.x) an instance of `type`. But the object instance which `__init__` acts on is an instance of `MyClass`, which is a completely different thing. – Kevin Jul 16 '18 at 01:00
  • @Happle, nothing automatically makes variables instantiated inside a method be attached to the instance -- methods can have local variables as much as anything else can. Thus, `self.foo = bar` is creating an instance method, but `foo = bar` is (inside method scope) creating a local. – Charles Duffy Jul 16 '18 at 01:01
  • @Happle **no**. Classes are *templates for instances*. That is how you should think about them. In Python, classes themselves *are also instances* of the `type` *meta*-class. But for now, don't worry about that if you are just starting OOP. – juanpa.arrivillaga Jul 16 '18 at 01:40

0 Answers0