Is not the same …

Usually, we don’t note  little, but relevant, differents in the code that we are reviewing. For example, the two next classes, apparently, are equivalents:

  class A:
    l = []
    __init__(self):
      ...
  class B:
    def __init__(self):
      self.l = []

    ...

But, really, this two classes are differ in their behavior:

  >>> a = A()
  >>> a.l.append(1)
  >>> a2 = A()
  >>> a2.l.append(2)
  >>> print a.l
  [1,2]
  >>> b = B()
  >>> b.l.append(1)
  >>> b2 = B()
  >>> b2.l.append(2)
  >>> print b.1
  [1]

Class A, due to l var is defined in class definition, share the l var between all A objects instanciates.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s