Class Methods with Python 2.1

F. GEIGER fgeiger at datec.at
Tue Apr 23 12:59:12 EDT 2002


I did this with PythonWin IDE:


from PyFL_0_1_1.static import static


class Car:

   __Availables = ["porsche", "volvo", "trabbi"]

   def __init__(self, name):
      if name not in Car.__Availables:
         raise Exception("Name not in available cars")
      return

   def Add_available_car(name):
      Car.__Availables.append(name)
      return
   Add_available_car = static(Add_available_car)

   def Available_cars():
      return Car.__Availables
   Available_cars = static(Available_cars)

   def available_cars(self):
      return Car.__Availables


def main():
   try:
      print 'Try to create my car: '
      myCar = Car('Benz')
   except Exception, e:
      print e
      print 'Add my car.'
      Car.Add_available_car('Benz')
      myCar = Car('Benz')

   print 'Cars available now: '
   print Car.Available_cars()
   print
   print myCar.available_cars()


if __name__ == '__main__':
   main()


To be able to run this, you need 'static':

class static:
   """
   SYNOPSIS:
      'Static-methods' (aka 'class-methods') in Python. Copied from Alex
Martelli's
      contribution in the ActiveState Python Cookbook.

   SAMPLE:
      class MyClass:
         def __init__(self):
            pass

         def myStaticMethod(self):
            pass

         myStaticMethod = static(myStaticMethod)

      def test():
         MyClass.myStaticMethod()

      test()
   """
   def __init__(self, anyCallable):
      self.__theCallable = anyCallable

   def __call__(self, *args, **kwds):
      return self.__theCallable(*args, **kwds)



This prints:

Try to create my car:
Name not in available cars
Add my car.
Cars available now:
['porsche', 'volvo', 'trabbi', 'Benz']

['porsche', 'volvo', 'trabbi', 'Benz']


Hope this helps

Cheers
Franz

"Thomas Guettler" <zopestoller at thomas-guettler.de> schrieb im Newsbeitrag
news:3CC57C5F.7040804 at thomas-guettler.de...
> Is it possible to have methods in classes
> which don't take a self argument, because
> they only change attributes common to all
> instances of a class?
>
> class car:
>      available=["porsche", "volvo", "trabbi"]
>      def __init__(self, name):
>         if name not in available:
>             raise "Name not in available cars"
>         ....
>      def add_available_car(name):
>          availalble.append(name)
>
> One solutionn is to define this method
> at module level. But that's not nice.
>
>
>
> Unfortunately I have to stick to Python2.1
>
>    thomas
>





More information about the Python-list mailing list