[Tutor] using class methods (security)

Paul Tremblay phthenry@earthlink.net
Tue, 23 Apr 2002 16:54:57 -0400


I am wondering if there is a good way to create class methods in
python.

I have included a simple script below to illustrate what I mean.

There seems to be no way to call on a class object directly in
python. Both methods I know of seem seem awkward:

(1)Modify the variable directly. For example, in the class below I
created a counter, called counter, which keeps track of many
Circle ojbects I have created. When I want to find out what the
counter is, I simply request the value for Circle.counter. But I
have been told you should never access a class variable directly.

(2)Use an object to access a class variable. For example, I
created a second counter called __counter. This counter is
private. In order to access it, I simply used an object method:

myCircleObject.numOfCircles()

It somehow seems wrong to access a class variable by using an
object, though I guess this second method should work, and seems
more secure and preferable to the first. 

Thanks!

Paul


#!/usr/bin/python

class Circle:
	__pi = 3.14159
	counter = 0
	__counter = 0 # desired method
     
	def __init__(self,radius=1):
		self.__radius=radius
		Circle.counter = Circle.counter +1
		Circle.__counter = Circle.__counter + 1 #desired method
          
	def area(self):
		return self.__radius * self.__radius * Circle.__pi
          
	def numOfCircles(self):
		print Circle.__counter
                
     
# This function gives simple accesses the class variable
# Circle.counter

def numCircles():
	total = 0
	print Circle.counter

myCircleObject = Circle(5)
print myCircleObject.area()
myCircle2Object = Circle()
print myCircleObject2.area()
numCircles() # access a class variable directly
Circle.counter = 100 # You can create a bogus number. Yikes!
numCircles() # prints out a bogus number
myCircleObject.numOfCircles() #object method to access class
						#variable


-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************