Moving from PHP to Python. Part Two

Jon Clements joncle at googlemail.com
Mon Dec 14 14:35:46 EST 2009


On Dec 14, 12:55 pm, Sancar Saran <sancar.sa... at evodot.com> wrote:
> Hello Again.
>
> I hope, I don't bug too much.
>
> First of all. I want to Thank to everyone who respond my messages.
>
> I was able to do some of my needs and stuck some others.
>
> So ? I need help again.
>
> And here my progress..
>
> Following was my globalized registry solution
>
> # -*- coding: utf-8 -*-
>
> class Registry:
>
>         data = {}
>
>         def __init__(self,environ):
>                 self.data['env'] = environ
>                 self.data['init'] = 'hede'
>
>         def set_entry(self,key,data):
>                 self.data[key] = data
>
>         def get_entry(self,key):
>                 return self.data[key]
>
>         def debug(self):
>
>                 r = '<pre>'
>                 r += repr(self.data)
>                 r += '</pre>'
>
>                 return r
>
> I have some questions about this code.

[snip]

On a side note -- data will be a class level attribute, rather than
I'm guessing a desired instance level one.

>>> class Blah:
	data = {}
	def __init__(self, whatever):
		self.data[whatever] = 'asfasdf'

>>> x = Blah(3)
>>> y = Blah(4)
>>> Blah.data
{3: 'asfasdf', 4: 'asfasdf'}
>>> x.data
{3: 'asfasdf', 4: 'asfasdf'}
>>> y.data
{3: 'asfasdf', 4: 'asfasdf'}

As opposed to:

>>> class Blah:
	def __init__(self, whatever):
		self.data = {}
		self.data[whatever] = 'asfasdf'


>>> x = Blah(3)
>>> y = Blah(4)
>>> x.data
{3: 'asfasdf'}
>>> y.data
{4: 'asfasdf'}
>>> Blah.data
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    Blah.data
AttributeError: class Blah has no attribute 'data'

Jon.



More information about the Python-list mailing list