instance creation

Andrew Thompson andrew.thompson at ashecastle.com
Tue Sep 24 11:11:23 CEST 2002


Dear Paul,

One simple way to do this is to define your single __init__ method to be
polymorphic, switch on the type of the first argument, and call the
appropriate method to complete the initialization.

'
class foo:
	def __init__(self, arg1 , arg2=None):
		if type(arg1)==type(string):
			self.init2(arg1,arg2)
		else:
			self.init3(arg1)

	def init2(name,details):
		blah blah

	def init3(id):
		blah blah

'



-----Original Message-----
From: python-list-admin at python.org [mailto:python-list-admin at python.org]
On Behalf Of Paul MG
Sent: 24 September 2002 09:52
To: python-list at python.org
Subject: instance creation

Hi

I am dabbling with Python and have run into a bit of an oddness. I
have a class Appointment, with fields Title and Details. I want to
allow two means of construction:

1) Providing Title and Details strings explicitly, to create a new
instance.
2) Providing an ID, which causes that Appointment to be loaded from a
backing store.

Now in C++ or smalltalk, I would do one of

- Provide two constructors:

    def __init__(self, name, details):
      self.name = name
      self.details = details

    def __init__(self, id):
      load(id)

    def load(self, id):
      i = open("appointment"+str(id))
      self = pickle.load(i)

- Provide a class method (creation method) to instantiate:

    def create(id):
      i = open("appointment"+str(id))
      return pickle.load(i)

However, much of this seems not to work.

- Having two constructors seems to be illegal - or at least the second
overwrites the first.
- Assigning to 'self' in the load method seems to really not work!
- Putting the create() method outside of the class works fine - but I
want it to be a class method on Appointment, goddammit!:) Is there no
way to do this?

Any help would be appreciated, basically i am looking for the python
idiom to do this, as my C++ and Smalltalk idiom's clearly aren't in
the grain of the language!

Thanks very much
Paul MG
-- 
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list