Explanation of Instance Variables in Python

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David MacQuigg

    Explanation of Instance Variables in Python


    I am writing a chapter for teaching OOP in Python. This chapter is
    intended as a brief introduction to replace the more complete
    discussion in Learning Python, 2nd ed, pp. 295-390. I need to explain
    instance variables.

    What I'm looking for is the best compromise between brevity and a full
    explanation. The students are non-CIS technical professionals (
    engineers and scientists ). At the point they need this explanation,
    they have covered functions and modules, but not classes. They are
    new to object-oriented programming. They have just been shown a class
    definition with some data attributes and methods.

    The non-CIS background is important, because I can't assume any
    experience with other computer languages.

    I would like to hear from users who have a similar background, or
    anyone who has taught such users. What is your background? Which of
    the alternatives below do you like or dislike? Can you think back on
    your own learning experience, and write something better?

    Here are some alternatives I have collected:

    1) Python Tutorial at http://docs.python.org/tut/node11.html
    ------------------------------------------------------------
    What exactly happens when a method is called? You may have noticed
    that x.f() was called without an argument above, even though the
    function definition for f specified an argument. What happened to the
    argument? Surely Python raises an exception when a function that
    requires an argument is called without any -- even if the argument
    isn't actually used...

    Actually, you may have guessed the answer: the special thing about
    methods is that the object is passed as the first argument of the
    function. In our example, the call x.f() is exactly equivalent to
    MyClass.f(x). In general, calling a method with a list of n arguments
    is equivalent to calling the corresponding function with an argument
    list that is created by inserting the method's object before the first
    argument.

    If you still don't understand how methods work, a look at the
    implementation can perhaps clarify matters. When an instance
    attribute is referenced that isn't a data attribute, its class is
    searched. If the name denotes a valid class attribute that is a
    function object, a method object is created by packing (pointers to)
    the instance object and the function object just found together in an
    abstract object: this is the method object. When the method object is
    called with an argument list, it is unpacked again, a new argument
    list is constructed from the instance object and the original argument
    list, and the function object is called with this new argument list.

    2) comp.lang.pytho n 4/27/04, David MacQuigg
    -------------------------------------------
    Some of the variables inside the methods in a class have a self.
    prefix. This is to distinguish local variables in the method from
    "instance variables". These instance variables will be found when the
    method is called, by searching the instance which called the method.
    The way this works is that calling the method from an instance causes
    that instance to be passed as the first argument to the method call.
    So if you call cat1.talk(), that is equivalent to Cat.talk(cat1) If
    you call cat1.set_vars( "Garfield", "Meow"), that is equivalent to
    Cat.set_vars(ca t1, "Garfield", "Meow")
    The "current instance" argument is automatically inserted as the first
    argument, ahead of any other arguments that you may provide in calling
    a method that is "bound" to an instance. Note: The distinction
    between instances and classes is important here. If you call a method
    from a class, that method is not bound to any instance, and you have
    to supply the instance explicitly in the first argument (
    Cat.talk(cat1) )
    The variable name self is just a convention. As long as you put the
    same name in the first argument as in the body of the definition, it
    can be self or s or even _ The single underscore is handy if you
    want to maximally suppress clutter.

    3) comp.lang.pytho n 4/27/04, Greg Ewing
    ---------------------------------------
    When a function is called from an instance (e.g. cat1.talk()), the
    instance is passed in as an extra parameter at the beginning of the
    parameter list, conventionally named 'self'. This allows you to refer
    to attributes of the instance as 'self.attrname' (e.g. self.sound).

    =============== =============== =======

    Thanks for your help on this project.

    -- Dave

    *************** *************** *************** *************** * *
    * David MacQuigg, PhD * email: dmq at gain.com * *
    * IC Design Engineer * phone: USA 520-721-4583 * * *
    * Analog Design Methodologies * * *
    * * 9320 East Mikelyn Lane * * *
    * VRS Consulting, P.C. * Tucson, Arizona 85710 *
    *************** *************** *************** *************** * *

  • Bengt Richter

    #2
    Re: Explanation of Instance Variables in Python

    On Wed, 28 Apr 2004 11:25:08 -0700, David MacQuigg <dmq@gain.com > wrote:
    [color=blue]
    >
    >I am writing a chapter for teaching OOP in Python. This chapter is
    >intended as a brief introduction to replace the more complete
    >discussion in Learning Python, 2nd ed, pp. 295-390. I need to explain
    >instance variables.
    >
    >What I'm looking for is the best compromise between brevity and a full
    >explanation. The students are non-CIS technical professionals (
    >engineers and scientists ). At the point they need this explanation,
    >they have covered functions and modules, but not classes. They are
    >new to object-oriented programming. They have just been shown a class
    >definition with some data attributes and methods.
    >
    >The non-CIS background is important, because I can't assume any
    >experience with other computer languages.
    >
    >I would like to hear from users who have a similar background, or
    >anyone who has taught such users. What is your background? Which of
    >the alternatives below do you like or dislike? Can you think back on
    >your own learning experience, and write something better?
    >
    >Here are some alternatives I have collected:
    >[/color]
    [... snip ...][color=blue]
    >
    >============== =============== ========
    >
    >Thanks for your help on this project.
    >[/color]
    I find well-annotated examples best for understanding something new.
    It also gives me working code to play with, to explore variations.
    How things break is often as instructive as how they work.

    I would suggest you encourage your students to experiment interactively.
    E.g., ask who can explain the following, and see what you get, and then
    collaborate with them to write sufficient comments to where they feel
    they "get it."
    [color=blue][color=green][color=darkred]
    >>> class C(object): pass[/color][/color][/color]
    ...[color=blue][color=green][color=darkred]
    >>> def f(*args): print 'f was called with', args[/color][/color][/color]
    ...[color=blue][color=green][color=darkred]
    >>> f('hello')[/color][/color][/color]
    f was called with ('hello',)[color=blue][color=green][color=darkred]
    >>> c=C()
    >>> c.f('hi')[/color][/color][/color]
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    AttributeError: 'C' object has no attribute 'f'[color=blue][color=green][color=darkred]
    >>> c.f = f
    >>> c.f('hi')[/color][/color][/color]
    f was called with ('hi',)[color=blue][color=green][color=darkred]
    >>> C.f = f
    >>> c.f('greetings' )[/color][/color][/color]
    f was called with ('greetings',)[color=blue][color=green][color=darkred]
    >>> del c.f
    >>> c.f('greetings' )[/color][/color][/color]
    f was called with (<__main__.C object at 0x00901330>, 'greetings')

    MRO can wait a little ;-)

    Regards,
    Bengt Richter

    Comment

    • Bengt Richter

      #3
      Re: Explanation of Instance Variables in Python

      On 29 Apr 2004 01:10:21 GMT, bokr@oz.net (Bengt Richter) wrote:
      [color=blue]
      >On Wed, 28 Apr 2004 11:25:08 -0700, David MacQuigg <dmq@gain.com > wrote:
      >[color=green]
      >>
      >>I am writing a chapter for teaching OOP in Python. This chapter is
      >>intended as a brief introduction to replace the more complete
      >>discussion in Learning Python, 2nd ed, pp. 295-390. I need to explain
      >>instance variables.[/color][/color]
      You might want to mention early that they are a special subset
      of object attributes, and that understanding the Python rules for accessing
      attributes in general is critical to understanding its implementation of OOP.[color=blue][color=green]
      >>
      >>============= =============== =========
      >>
      >>Thanks for your help on this project.
      >>[/color]
      >I find well-annotated examples best for understanding something new.
      >It also gives me working code to play with, to explore variations.
      >How things break is often as instructive as how they work.
      >
      >I would suggest you encourage your students to experiment interactively.
      >E.g., ask who can explain the following, and see what you get, and then
      >collaborate with them to write sufficient comments to where they feel
      >they "get it."
      >[/color]
      Actually, looking at my previous example, maybe this would give more hints,
      in case they don't discover for themselves (strongly urge teaching how to
      fish, not serving fish, though ;-):
      [color=blue][color=green][color=darkred]
      >>> class C(object): pass[/color][/color][/color]
      ...[color=blue][color=green][color=darkred]
      >>> def f(*args): print 'f was called with', args[/color][/color][/color]
      ...[color=blue][color=green][color=darkred]
      >>> f[/color][/color][/color]
      <function f at 0x008FDEB0>[color=blue][color=green][color=darkred]
      >>> C[/color][/color][/color]
      <class '__main__.C'>[color=blue][color=green][color=darkred]
      >>> f('hello')[/color][/color][/color]
      f was called with ('hello',)[color=blue][color=green][color=darkred]
      >>> c=C()
      >>> c[/color][/color][/color]
      <__main__.C object at 0x00901370>[color=blue][color=green][color=darkred]
      >>> c.f('hello')[/color][/color][/color]
      Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      AttributeError: 'C' object has no attribute 'f'[color=blue][color=green][color=darkred]
      >>> c.f = f
      >>> c.f[/color][/color][/color]
      <function f at 0x008FDEB0>[color=blue][color=green][color=darkred]
      >>> c.f('hello')[/color][/color][/color]
      f was called with ('hello',)[color=blue][color=green][color=darkred]
      >>> C.f = f
      >>> c.f[/color][/color][/color]
      <function f at 0x008FDEB0>[color=blue][color=green][color=darkred]
      >>> c.f('hello')[/color][/color][/color]
      f was called with ('hello',)[color=blue][color=green][color=darkred]
      >>> del c.f
      >>> c.f[/color][/color][/color]
      <bound method C.f of <__main__.C object at 0x00901370>>[color=blue][color=green][color=darkred]
      >>> c.f('hello')[/color][/color][/color]
      f was called with (<__main__.C object at 0x00901370>, 'hello')

      Regards,
      Bengt Richter

      Comment

      • David MacQuigg

        #4
        Re: Explanation of Instance Variables in Python

        On 29 Apr 2004 01:30:55 GMT, bokr@oz.net (Bengt Richter) wrote:
        [color=blue]
        >On 29 Apr 2004 01:10:21 GMT, bokr@oz.net (Bengt Richter) wrote:[/color]
        [color=blue][color=green]
        >>I find well-annotated examples best for understanding something new.
        >>It also gives me working code to play with, to explore variations.
        >>How things break is often as instructive as how they work.
        >>
        >>I would suggest you encourage your students to experiment interactively.
        >>E.g., ask who can explain the following, and see what you get, and then
        >>collaborate with them to write sufficient comments to where they feel
        >>they "get it."
        >>[/color]
        >Actually, looking at my previous example, maybe this would give more hints,
        >in case they don't discover for themselves (strongly urge teaching how to
        >fish, not serving fish, though ;-):
        >[color=green][color=darkred]
        > >>> class C(object): pass[/color][/color]
        > ...[color=green][color=darkred]
        > >>> def f(*args): print 'f was called with', args[/color][/color]
        > ...[color=green][color=darkred]
        > >>> f[/color][/color]
        > <function f at 0x008FDEB0>[color=green][color=darkred]
        > >>> C[/color][/color]
        > <class '__main__.C'>[color=green][color=darkred]
        > >>> f('hello')[/color][/color]
        > f was called with ('hello',)[color=green][color=darkred]
        > >>> c=C()
        > >>> c[/color][/color]
        > <__main__.C object at 0x00901370>[color=green][color=darkred]
        > >>> c.f('hello')[/color][/color]
        > Traceback (most recent call last):
        > File "<stdin>", line 1, in ?
        > AttributeError: 'C' object has no attribute 'f'[color=green][color=darkred]
        > >>> c.f = f
        > >>> c.f[/color][/color]
        > <function f at 0x008FDEB0>[color=green][color=darkred]
        > >>> c.f('hello')[/color][/color]
        > f was called with ('hello',)[color=green][color=darkred]
        > >>> C.f = f
        > >>> c.f[/color][/color]
        > <function f at 0x008FDEB0>[color=green][color=darkred]
        > >>> c.f('hello')[/color][/color]
        > f was called with ('hello',)[color=green][color=darkred]
        > >>> del c.f
        > >>> c.f[/color][/color]
        > <bound method C.f of <__main__.C object at 0x00901370>>[color=green][color=darkred]
        > >>> c.f('hello')[/color][/color]
        > f was called with (<__main__.C object at 0x00901370>, 'hello')[/color]

        I like this example. It shows clearly how the first argument is
        inserted in the calling sequence for a normal method call. I remember
        that seemed very strange when I was learning Python.

        -- Dave

        Comment

        Working...