
-----------------------------------
wtd
Tue Nov 08, 2005 3:54 pm

[Python-tut] Private Instance Variables
-----------------------------------
So you've created an object in Python:

class StudentRecord(object):
   def __init__(self, name, grades = 

And you create an instance:

bob = StudentRecord("Bob", 

Now, it's pretty obvious that if you call:

bob.max_grade()

You should get 100.  But what if I was an idiot and wrote:

bob.grades = 

What will Python do to stop me?

Python won't do a darn thing, because the grades list was public.

So, the question is how we go about making it private.

class StudentRecord(object):
   def __init__(self, name, grades = 

That's great, but now how do I get to that list in a read-only fashion?

class StudentRecord(object):
   def __init__(self, name, grades = 

Or alternatively:

class StudentRecord(object):
   def __init__(self, name, grades = 

The property function can also be used to create "setters" as well as "getters".

-----------------------------------
Mazer
Tue Nov 08, 2005 4:48 pm


-----------------------------------
This is great! I was hoping that something like this existed.

-----------------------------------
[Gandalf]
Tue Nov 08, 2005 4:53 pm


-----------------------------------
Something I can learn :).  I'll go through it once I learn a bit more of the basics...
