1

I'm not sure if the output of this code is correct or a bug:

class F:
  """An abstract class"""
  list_of_secrets = []
  def __init__(self):
    pass

  def getSecret(self):
    return self.list_of_secrets

class F_None(F):
  pass

class F_Some(F):
  def __init__(self):
    self.list_of_secrets.append("secret value!")

x = F_Some()
print "x:",x.getSecret()

y = F_None()
print "y:",y.getSecret()

The output using python 2.7.3:

x: ['secret value!']

y: ['secret value!']

I think it should output:

x: ['secret value!']

y: []

Any thoughts?

Pedro del Sol
  • 2,840
  • 9
  • 39
  • 52
user1234299
  • 1,017
  • 1
  • 8
  • 14

2 Answers2

2

list_of_secrets is scoped to the class here. You want to instead attach it to self in __init__

  def __init__(self):
      self.list_of_secrets = []
Doug T.
  • 64,223
  • 27
  • 138
  • 202
1

You never define self.list_of_secrets. You only define F.list_of_secrets, which is entirely different. Do this instead:

class F:
  """An abstract class"""
  def __init__(self):
    self.list_of_secrets = []

  def getSecret(self):
    return self.list_of_secrets
Waleed Khan
  • 11,426
  • 6
  • 39
  • 70