473,902 Members | 4,667 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloading __init__

92 New Member
Working on a class that I would use multiple constructors in C++ since I have different ways of creating the data. Tried this in python by defining multiple __init__ methods but to no avail, it seems to only find the second one. So I have:
Expand|Select|Wrap|Line Numbers
  1. class myclass:
  2.   __init__ (self, mystring1, mystring2)
  3.           self.name = mystring1
  4.           self.value = mystring2
  5.  
  6.   __init__ (self, xmldoc):
  7.           <some code to parse the XML into my attrs>
  8.  

Now my class is way more complex then that, but I just want multiple __init__ methods, with different signatures, to insantite my objects. When i try to use the first one it says "TypeError: __init__() takes exactly 2 arguments (3 given)" using the second version of __init__ does work. Thoughts?
Jan 29 '08 #1
4 16361
bvdet
2,851 Recognized Expert Moderator Specialist
Working on a class that I would use multiple constructors in C++ since I have different ways of creating the data. Tried this in python by defining multiple __init__ methods but to no avail, it seems to only find the second one. So I have:
Expand|Select|Wrap|Line Numbers
  1. class myclass:
  2.   __init__ (self, mystring1, mystring2)
  3.           self.name = mystring1
  4.           self.value = mystring2
  5.  
  6.   __init__ (self, xmldoc):
  7.           <some code to parse the XML into my attrs>
  8.  

Now my class is way more complex then that, but I just want multiple __init__ methods, with different signatures, to insantite my objects. When i try to use the first one it says "TypeError: __init__() takes exactly 2 arguments (3 given)" using the second version of __init__ does work. Thoughts?
It makes sense that only the second __init__ would work. Why not something like this:
Expand|Select|Wrap|Line Numbers
  1. class myclass(object):
  2.     def __init__ (self, arg1, arg2=None):
  3.         if isinstance(arg1, minidom.Document):
  4.             <some code to parse the XML into your attrs>
  5.         else:
  6.             self.name = arg1
  7.             self.value = arg2
where minidom.Documen t is whatever type of XML document you are passing.
Jan 29 '08 #2
Benny the Guard
92 New Member
That works, just seems counter-intuitive since all other methods can be overloaded (and it's a basic element of OO design). If overriding __init__ is not possible, can Python really claim to be fully OO?

What I just tried was using staticmethod factories to create it, this keeps my logic separate (and my real init logic is pretty big for each case). So I have:

Expand|Select|Wrap|Line Numbers
  1. class myclass:
  2. def __init__(self)
  3.   c.name = ''
  4.   c.value = ''
  5.  
  6. def CreateFromStrs (mystring0, mystring1):
  7.   c = myclass
  8.   c.name = mystring0
  9.   c.value = mystring1
  10.   return c
  11. CreateFromStrings = staticmethod (CreateFromStrs)
  12.  
  13. def CreateFromXML (xmldata):
  14.   c = myclass ()
  15.   <...>
  16.   return c
  17. CreateFromXml = staticmethod (CreateFromXml)
  18.  
  19. Then later.
  20.  
  21. myclass1 = myclass.CreateFromXml (xml)
  22. myclass2 = myclass.CreateFromStrs ('hellow', 'world')

I will chalk it up to one of those Python oddities. Minor annoyance, just makes me comment more, which is probably good anyway. Thanks for the help.
Jan 29 '08 #3
William Manley
56 New Member
but python *does* override it. It defines the first __init__ function and then, overrides it, when you define the second __init__ function.

its not a matter of being OO, its a matter of using the same name.
Jan 30 '08 #4
elcron
43 New Member
If you want the __init__'s to be seperate you could subclass but I prefer bvdet's way better.
Jan 31 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

1
2053
by: Fuzzyman | last post by:
I've been programming in python for a few months now - and returning to programming after a gap of about ten years I've really enjoyed learning python. I've just made my first forays into inheritance and operator overloading (both concepts that I initially found hard to grasp). I've written a simple config file parser - and I thought I'd experiment with making the interface easier by subclassing dict and overloading the __setitem__,...
2
5269
by: Sergey Krushinsky | last post by:
Hello all, Is there a common way to emulate constructor overloading in Python class? For instanse, I have 3 classes: 1/ Polar - to hold polar coordinates; 2/ Cartesian - to hold cartesian coordinates; 3/ Coordinates3D, which holds synchronized instances of the both in __p__ and __c__ fields respectively.
33
2547
by: Jacek Generowicz | last post by:
I would like to write a metaclass which would allow me to overload names in the definition of its instances, like this class Foo(object): __metaclass__ = OverloadingClass att = 1 att = 3
7
2179
by: Doran_Dermot | last post by:
Hi All, I've seen lots of code in which the attributes of a class are accessed and modified using two separate methods. For example: class Problems: def __init__( self, refNum ): self._refNum = refNum self._title = "" self._problem = ""
9
1717
by: Martin Häcker | last post by:
Hi there, I just tried to run this code and failed miserably - though I dunno why. Could any of you please enlighten me why this doesn't work? Thanks a bunch. --- snip --- import unittest from datetime import datetime
4
6634
by: John M. Gabriele | last post by:
I know that Python doesn't do method overloading like C++ and Java do, but how am I supposed to do something like this: --------------------- incorrect ------------------------ #!/usr/bin/python class Point3d: pass
3
2896
by: Iyer, Prasad C | last post by:
I am new to python. I have few questions a. Is there something like function overloading in python? b. Can I overload __init__ method Thanks in advance regards
11
28167
by: placid | last post by:
Hi all, Is it possible to be able to do the following in Python? class Test: def __init__(self): pass def puts(self, str): print str
9
3527
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by allowing the assignment operator (=) to be overloaded. One particular use for this would be to implement "lazy evaluation". For example it would allow us to get rid of all the temporary arrays produced by NumPy. For example, consider the...
0
9997
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9845
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10870
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
10981
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
10499
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9673
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...
0
5893
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
6085
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3323
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.