473,386 Members | 1,763 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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.python 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(cat1, "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.python 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 *
************************************************** *********** *

Jul 18 '05 #1
3 2492
On Wed, 28 Apr 2004 11:25:08 -0700, David MacQuigg <dm*@gain.com> wrote:

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:
[... snip ...]
=====================================

Thanks for your help on this project.

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."
class C(object): pass ... def f(*args): print 'f was called with', args ... f('hello') f was called with ('hello',) c=C()
c.f('hi') Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'f' c.f = f
c.f('hi') f was called with ('hi',) C.f = f
c.f('greetings') f was called with ('greetings',) del c.f
c.f('greetings')

f was called with (<__main__.C object at 0x00901330>, 'greetings')

MRO can wait a little ;-)

Regards,
Bengt Richter
Jul 18 '05 #2
On 29 Apr 2004 01:10:21 GMT, bo**@oz.net (Bengt Richter) wrote:
On Wed, 28 Apr 2004 11:25:08 -0700, David MacQuigg <dm*@gain.com> wrote:

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. 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.

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

Thanks for your help on this project.

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."

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 ;-):
class C(object): pass ... def f(*args): print 'f was called with', args ... f <function f at 0x008FDEB0> C <class '__main__.C'> f('hello') f was called with ('hello',) c=C()
c <__main__.C object at 0x00901370> c.f('hello') Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'f' c.f = f
c.f <function f at 0x008FDEB0> c.f('hello') f was called with ('hello',) C.f = f
c.f <function f at 0x008FDEB0> c.f('hello') f was called with ('hello',) del c.f
c.f <bound method C.f of <__main__.C object at 0x00901370>> c.f('hello')

f was called with (<__main__.C object at 0x00901370>, 'hello')

Regards,
Bengt Richter
Jul 18 '05 #3
On 29 Apr 2004 01:30:55 GMT, bo**@oz.net (Bengt Richter) wrote:
On 29 Apr 2004 01:10:21 GMT, bo**@oz.net (Bengt Richter) wrote:

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."

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 ;-):
class C(object): pass ... def f(*args): print 'f was called with', args ... f <function f at 0x008FDEB0> C <class '__main__.C'> f('hello') f was called with ('hello',) c=C()
c <__main__.C object at 0x00901370> c.f('hello') Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'f' c.f = f
c.f <function f at 0x008FDEB0> c.f('hello') f was called with ('hello',) C.f = f
c.f <function f at 0x008FDEB0> c.f('hello') f was called with ('hello',) del c.f
c.f <bound method C.f of <__main__.C object at 0x00901370>> c.f('hello')

f was called with (<__main__.C object at 0x00901370>, 'hello')


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

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

34
by: SeeBelow | last post by:
I see the value of a class when two or more instances will be created, but Python programmers regularly use a class when there will only be one instance. What is the benefit of this? It has a...
8
by: Paul Cochrane | last post by:
Hi all, I've got an application that I'm writing that autogenerates python code which I then execute with exec(). I know that this is not the best way to run things, and I'm not 100% sure as to...
4
by: PaulR | last post by:
Hi, We have a Server running SLES 8 and 3GB memory, with 1 DB2 instance and 2 active Databases. General info... DB2level = "DB2 v8.1.0.72", "s040914", "MI00086", and FixPak "7" uname -a =...
28
by: Stef Mientki | last post by:
hello, I'm trying to build a simple functional simulator for JAL (a Pascal-like language for PICs). My first action is to translate the JAL code into Python code. The reason for this approach is...
25
by: Erik Lind | last post by:
I'm new to Python, and OOP. I've read most of Mark Lutz's book and more online and can write simple modules, but I still don't get when __init__ needs to be used as opposed to creating a class...
2
by: Nikolaus Rath | last post by:
Hello, I am really surprised that I am asking this question on the mailing list, but I really couldn't find it on python.org/doc. Why is there no proper way to protect an instance variable...
1
by: BrendanC | last post by:
I'm trying to understand reflection/introspection in Python. How can I identify the the type of attribute (e.g. instance var) in a class? The following returns all the class attributes (methods and...
16
by: DamienS | last post by:
In the interests of me saving hair, can someone please explain to me what's going on below? Why doesn't == work in comparing two int's when cast as objects? They're the same type. Note that it...
275
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.