| |||||||||||
| |||||||||||
__new__ v __init__ - python constructor alternatives?
The constructor you'll normally override (and call when you create an object) in Python is called __init__, but there is also a method called __new__ available to the class author.
Here's a code sample showing three classes with a mixture of different constructors. class A(object):And here's the result of running that code: 40:~/ndfi grahamellis$ python newvinitIn class C, there's only an __init__ so that's run. Class A has both, and so the __new__ take precedence. In class B, the __new__ takes precendence but it makes an apparent recursive call that's been diverted to __init__ as something of a safeguard - for illustrative purposes, this one! When would you use __new__? 1. When you want you constructor to return an object of a different type to the class in which it is defined. For example, you have a class "animal" with subclasses "farmanimal" and "pet" and you want the animal cosntructor to be able to examine the data passed in to it and return an animal ... OR a farmanimal OR a pet depending on that data. 2. It has been suggested that experienced base class programmers override __new__ to discourage programmers who subclass them from overwriting their constructors. Personally, I would suggest that a good training course is better than this form of security through obscurity. (written 2007-04-14 07:20:47) Associated topics are indexed under Y112 - Python - Objects - IntermediateY212 - Further advanced features of Python
Some other Articles
Helsinki - what comes naturallyTurning objects into something you can store - Pickling (Python) Python decorators - wrapping a method call in extra code A picture (mostly in words) of Helsinki __new__ v __init__ - python constructor alternatives? Using a list of keys and a list of values to make a dictionary in Python - zip Python dictionary for quick look ups A course in Helsinki Planters in the Spring A strong team broadens the professional coverage 1638 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 at 50 posts per pageThis is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price. Link to Ezine home page (for reading). Link to Blogging home page (to add comments). |
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho | |||||||||||