[Tutor] A class that instantiates conditionally ?

Knacktus knacktus at googlemail.com
Wed Mar 2 17:03:28 CET 2011

Am 01.03.2011 07:49, schrieb David:
> 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.

I think that's too clever ;-). Instead, you could create a function 
which has the only and explicit purpose to decide wether or not to 
create the class, e.g.

def class_for_condition(condition):
     if condition:
         return MyClass()
     return None

and use this throughout your code, e.g.

my_object = class_for_condition(condition)

But to me, it sounds a bit like trouble in general. As Alan said, you 
have to deal with two options for my_object in the remaining code. I 
can't really judge without seeing what you want to do later on, but 
maybe you have the chance to branch on a higher abstraction level?

if condition:
     do_all_this_stuff() # do the things with my_object
     do_the_other_stuff() # do the things you don't need my_object



> 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:
> 		pass
> 	condition = 0
> 	if condition:
> 		my_object = MyClass()
> 	else:
> 		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)
> 			else:
> 				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?
> Thanks.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list