473,795 Members | 2,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can __init__ not return an object?

When I go to create an object I want to be able to decide whether the
object is valid or not in __init__, and if not, I want the constructor to
return something other than an object, (like maybe None). I seem to be
having problems. At the end of __init__ I say (something like)

if self.something < minvalue:
del self
return None

and it doesn't work. I first tried just the return None, then I got crafty
and tried the del self. Is what I'm trying to do possible in the
constructor or do I have to check after I return? Or would raising an
exception in the constructor be appropriate?

Am I even being clear?

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Apr 22 '07 #1
3 10379
On Sat, 21 Apr 2007 22:36:42 -0400, Steven W. Orr wrote:
When I go to create an object I want to be able to decide whether the
object is valid or not in __init__, and if not, I want the constructor to
return something other than an object, (like maybe None).
None is an object, like everything else in Python.

__init__ is not a constructor, it is an initializer -- by the time
__init__ is called, the instance is already constructed.

__init__ is expected to return None.
>>class Foo(object):
.... def __init__(self):
.... return 2
....
>>f = Foo()
__main__:1: RuntimeWarning: __init__() should return None
I seem to be
having problems. At the end of __init__ I say (something like)

if self.something < minvalue:
del self
return None

and it doesn't work.
del self doesn't really do anything useful there, except unbind the name
"self" from the instance.

"return None" is redundant, because all functions and methods will
automatically return None if you don't specify differently.
I first tried just the return None, then I got crafty
and tried the del self. Is what I'm trying to do possible in the
constructor or do I have to check after I return? Or would raising an
exception in the constructor be appropriate?
Yes, absolutely raise an exception.

--
Steven.

Apr 22 '07 #2
On Apr 22, 3:36 am, "Steven W. Orr" <ste...@syslang .netwrote:
When I go to create an object I want to be able to decide whether the
object is valid or not in __init__, and if not, I want the constructor to
return something other than an object, (like maybe None).
[...]

__init__ doesn't create an instance, it initializes it, i.e. does
things like settings some attributes, etc. The method that creates
instances is called __new__ (see http://docs.python.org/ref/customization.html).

--
Arnaud

Apr 22 '07 #3
On Apr 22, 4:36 am, "Steven W. Orr" <ste...@syslang .netwrote:
When I go to create an object I want to be able to decide whether the
object is valid or not in __init__, and if not, I want the constructor to
return something other than an object, (like maybe None). I seem to be
having problems. At the end of __init__ I say (something like)

if self.something < minvalue:
del self
return None

and it doesn't work. I first tried just the return None, then I got crafty
and tried the del self. Is what I'm trying to do possible in the
constructor or do I have to check after I return? Or would raising an
exception in the constructor be appropriate?
You can raise an exception of course but it would just create a side
effect. Another way to achieve what you request for is manipulating
the class creation mechanism.

class A(object):
def __new__(cls, x):
if x == 0:
return None
obj = object.__new__( cls)
obj.__init__(x)
return obj

class B(A):
def __init__(self, x):
self.x = x

The condition can always be checked within the static __new__ method.

Kay

Apr 23 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6692
by: never-aways | last post by:
How do you return an object from a function? Take the following snippet... class Stuff { public $nNum; public $szText; } function MakeStuff
1
3903
by: Batista, Facundo | last post by:
Studying the Tim Peter's FixedPoint code, found this: # can we coerce to a float? yes = 1 try: asfloat = float(value) except: yes = 0 if yes: self.__init__(asfloat, p)
5
3756
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const reference. now, casting a const return object from a function to a non-const reference to this...
4
5459
by: surindersaini | last post by:
Hi I am not sure if we can do it and if can, then how. I have a class with a property that return object as its return type. when i am trying to Serialize the class it gives me error **************************************************************** An unhandled exception of type 'System.InvalidOperationException' occurred in system.xml.dll Additional information: There was an error generating the XML document.
0
1792
by: Henke | last post by:
Hi I have a webservice that should return a result object, like this: public class Result { private object data; private int status; public object Data { get{return data;}
0
1144
by: hazz | last post by:
After generating an XML Web Service proxy class using wsdl.exe, I added a proxy class to a new VS2005 project to consume my webservice. I want to call the method ReturnCustomer() whose proxy details are below and assign the array of the object the return value of the function Service s = new Service(); Customer = s.ReturnCustomer; or object = s.ReturnCustomer(); The designtime debugger throws an error for s.ReturnCustomer() saying " No...
12
2268
by: acb | last post by:
Hi, I have a list of different objects in a <List> Structure. There is only one category of each kind of object. Current I have the following methods: public static Flag GetFlagObj() { foreach (Thingy s in _Thingies)
9
4010
by: Alexander Widera | last post by:
hi, is it possible to return an object of an unknown (but not really unknown) type with an method? i have the following situation: - a variable (A) of the type "object" which contains the object - a variable (B) of the type "Type" which contains the type of the object in (A) (A should be of the type B) - a method which should return the object (A) as type (B)
22
1950
by: Michael Pradel | last post by:
Hi all, I just returned to C++ after programming in other languages, and find myself a bit puzzled about the following issue: (see attached code). How can I avoid the deletion of an object that is returned by a method? Is returning a clone of it the only possibility? That would use a lot of memory in case of larger objects.
3
1695
by: MathWizard | last post by:
Hi, I have a question about returning an object in a function and calling a copy constructor. As far as I understand, in the following code the copy constructor may or may not be called, depending on the compiler: A what() { A my_A; // do something with A.
0
10216
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7543
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2921
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.