[Tutor] A class that instantiates conditionally ?

Steven D'Aprano steve at pearwood.info
Wed Mar 2 10:44:43 CET 2011

Alan Gauld wrote:
> "David" <bouncingcats at gmail.com> wrote
>> clever enough to refuse to instantiate itself if a necessary condition
>> is not met.
>> class MyClass_2(object):
>>     def __new__(self, condition):
>>          if condition:
>>                return object.__new__(self)
>>          else:
>>                return None
> Thats pretty much how I'd do it.

By convention, the name of the first argument to __new__ is cls, not 
self, because it is bound to the class object itself (MyClass_2 in this 
example) rather than the instance. The instance doesn't yet exist, so 
that's not surprising!


More information about the Tutor mailing list