extend class: include factories functions inside constructor

aspineux aspineux at gmail.com
Thu Aug 18 09:44:38 EDT 2011


Hi
I have a closed class and 2 factories function

class Data:
  def __init__(self):
    self.payload=None

def data_from_string(payload):
  data=Data()
  data.payload=payload
  return data

def data_from_file(f):
  data=Data()
  data.payload=f.read()
  return data

And I want to extend the class, by first including the factories
function inside the constructor,
second add some method to the class.

class MyData(Data):

  def __init__(self, arg):
    # I know this coke is not working, this is to show you
    # what I expect
    if isinstance(arg, file):
        self=data_from_file(arg)
    else:
        self=data_from_string(arg)
    return self

  def len(self):
    return len(self.payload)

And how I want to use it

>>> m=MyData('hello')
>>> print m.len()
5

any idea ?

Alain



More information about the Python-list mailing list