[Tutor] A class that instantiates conditionally ?

David bouncingcats at gmail.com
Tue Mar 1 07:49:02 CET 2011

I have an idea that might clean up my code slightly, if I can make one
of my classes
clever enough to refuse to instantiate itself if a necessary condition
is not met.

Below I propose some example code that seems to achieve this, and I am
asking here
for feedback on it, because I have not written much python. So I might be doing
something unwise due to fiddling with things I don't totally understand.

My aim is that instead of writing this:

	class MyClass:

	condition = 0

	if condition:
		my_object = MyClass()
		my_object = None

I could instead write this:

	class MyClass_2:
		# put the if-test here inside the class

	my_object_2 = MyClass_2(condition)

to achieve the goal that (my_object_2 == None) when (condition == False).

I read the (ver 2.6) Python Language Reference
 Section 3.4.1. Basic customization
 Section 3.4.3. Customizing class creation

Most of the content there is way beyond my current understanding, but I came up
with the following code, which seems to work:

	class MyClass_2(object):
		def __new__(self, condition):
			if condition:
				return object.__new__(self)
				return None

	condition = 0
	my_object_2 = MyClass_2(condition)
	print my_object_2
	condition = 1
	my_object_2 = MyClass_2(condition)
	print my_object_2

Can anyone see any technical or style issues with that? Or
alternatively reassure me that it is completely ok?

More information about the Tutor mailing list