473,654 Members | 2,974 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class factory functions

Here's a simple class-factory function that returns a sub-class of the
old-style class it is passed.

def verbosify_oclas s(klass):
"""Returns a verbose sub-class of old-style klass."""
class VClass(klass):
def __init__(self, *args, **kwargs):
print "Calling initializer __init__ ..."
klass.__init__( self, *args, **kwargs)
return VClass
Here it is in action:
>>class Parrot:
.... def __init__(self, colour): self.colour = colour
....
>>VParrot = verbosify_oclas s(Parrot)
bird = VParrot('red')
Calling initializer __init__ ...
>>bird.colour
'red'
Here's an equivalent for new-style classes. It uses super() because I
understand that super() is preferred to calling the super-class by name.
def verbosify_nclas s(klass):
"""Returns a verbose sub-class of new-style klass."""
class VClass(klass):
def __new__(cls, *args, **kwargs):
print "Calling constructor __new__ ..."
return super(klass, cls).__new__(cl s, *args, **kwargs)
def __init__(self, *args, **kwargs):
print "Calling initializer __init__ ..."
super(klass, self).__init__( *args, **kwargs)
return VClass

But it doesn't work:
>>vint = verbosify_nclas s(int)
vint(42)
Calling constructor __new__ ...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __new__
TypeError: object.__new__( VClass) is not safe, use int.__new__()
What am I doing wrong?
Here's one solution: dump the call to super() and call the super-class
directly. It seems to work. Are there any problems in not using super()?
What about multiple inheritance?
def verbosify_nclas s2(klass):
"""Returns a verbose sub-class of new-style klass."""
class VClass(klass):
def __new__(cls, *args, **kwargs):
print "Calling constructor __new__ ..."
return klass.__new__(k lass, *args, **kwargs)
def __init__(self, *args, **kwargs):
print "Calling initializer __init__ ..."
super(klass, self).__init__( *args, **kwargs)
return VClass

--
Steven.

Mar 25 '07 #1
2 1649
Steven D'Aprano wrote:
Here's a simple class-factory function that returns a sub-class of the
old-style class it is passed.

def verbosify_oclas s(klass):
"""Returns a verbose sub-class of old-style klass."""
class VClass(klass):
def __init__(self, *args, **kwargs):
print "Calling initializer __init__ ..."
klass.__init__( self, *args, **kwargs)
return VClass
Here it is in action:
>>>class Parrot:
... def __init__(self, colour): self.colour = colour
...
>>>VParrot = verbosify_oclas s(Parrot)
bird = VParrot('red')
Calling initializer __init__ ...
>>>bird.colou r
'red'
Here's an equivalent for new-style classes. It uses super() because I
understand that super() is preferred to calling the super-class by name.
def verbosify_nclas s(klass):
"""Returns a verbose sub-class of new-style klass."""
class VClass(klass):
def __new__(cls, *args, **kwargs):
print "Calling constructor __new__ ..."
return super(klass, cls).__new__(cl s, *args, **kwargs)
def __init__(self, *args, **kwargs):
print "Calling initializer __init__ ..."
super(klass, self).__init__( *args, **kwargs)
return VClass

But it doesn't work:
>>>vint = verbosify_nclas s(int)
vint(42)
Calling constructor __new__ ...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __new__
TypeError: object.__new__( VClass) is not safe, use int.__new__()
What am I doing wrong?
Why would you skip VClass in the super() calls? This should work:

def verbosify_nclas s(klass):
"""Returns a verbose sub-class of new-style klass."""
class VClass(klass):
def __new__(cls, *args, **kwargs):
print "Calling constructor __new__ ..."
return super(VClass, cls).__new__(cl s, *args, **kwargs)
def __init__(self, *args, **kwargs):
print "Calling initializer __init__ ..."
super(VClass, self).__init__( *args, **kwargs)
return VClass

Peer
Mar 25 '07 #2
On Sun, 25 Mar 2007 11:58:00 +0200, Peter Otten wrote:
>But it doesn't work:
>>>>vint = verbosify_nclas s(int)
vint(42)
Calling constructor __new__ ...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __new__
TypeError: object.__new__( VClass) is not safe, use int.__new__()
What am I doing wrong?

Why would you skip VClass in the super() calls?

That's a good question. If I every get a good answer, I'll let you know.
This should work:
[snip]

As indeed it seems like it does.

Thank you,

--
Steven.

Mar 25 '07 #3

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

Similar topics

39
3156
by: Marco Aschwanden | last post by:
Hi I don't have to talk about the beauty of Python and its clear and readable syntax... but there are a few things that striked me while learning Python. I have collected those thoughts. I am sure there are many discussions on the "problems" mentioned here. But I had this thoughts without looking into any forums or anything... it is kind of feedback.
17
4802
by: Aguilar, James | last post by:
My previous example used the concept of a Shape class heirarchy, so I will continue with that. Suppose I have something like fifty different shapes, and I am trying to instantiate one of them. The trick is, the instatiation will be based on a string with the exact same name as the type that I am trying to instantiate. Obviously, writing a fifty element long switch statement is an inferior solution. So, how can I instantiate based on...
0
942
by: Hatim Ali | last post by:
Hi, I've subclassed two classes inside classA. Theses subclasses are derived from classA. There are some virtual functions in classA with their implementation defined in those subclasses. Client can only see classA. Instances of classA will be created by a class factory. On basis of parameters passed to class factory, the factory creates new objects of subclasses and returns them to client. Following snippet demonstrates the idea. public...
11
1823
by: Manuel | last post by:
Hi, I need implement a map of member functions of some class. This map is formed by a string and a pointer to the member function. The problem is that the map need that the object saved are the same type. So what type to specify in the declaration of the map? map<std::string,void *¿?
16
3887
by: Manuel | last post by:
hi, In the past I made the question "how to implement a simple class forname". I made this finally and it compiled well. but now when i execute the program, it crash with a sigsegv. The code is this: FACTORY_H
5
2507
by: mmatchyn | last post by:
I have been trying to create a class similar to SqlClient but one that prints sql statements instead of running them on the database. This way when I want to go into test mode I comment out the SqlClient class and comment in the test class. The problem I am facing now is I have to limit myself to simple functions for the SqlDataReader class. I would like to copy in the SqlDataReader object exactly the way it is so that I can use this...
6
4214
by: GroupReader | last post by:
In my app, I have two very similar static classes. After long thought, I've decided *yes - keep them static*. - Sometimes I will want to use Static Class A, and somtimes I will want to use Static Class B, depending on the situation. - The interfaces (are interfaces allowed on static classes?) are almost identical. What's the best way in code to create some sort of "factory" that will
11
3092
by: digz | last post by:
Hello, Apologies if this is the wrong group for this question. I want to design an interface , where for a custom functionality , the client writes a new class with the function implementation and then puts the name of the Class as a configuration parameter or something and then the main program loads the new class like a module and the client can now write code using the new Functions. I suppose this problem has been solved before , if...
4
2683
by: =?Utf-8?B?SmVzc2ljYQ==?= | last post by:
Hi All, I know that I can use the GetProcAddress to get the proc address of a global exported function from a WIn32 dll. But if I have an exported class in the dll, is there a way to dynamically load this dll and get an instance of this class? (No static linking with the lib file) I am currently thinking about having global exported functions which internally calls the member functions of the class's single instance. These global...
44
2920
by: Steven D'Aprano | last post by:
I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! "Abstract class" isn't right, because that implies that you should subclass the class and then instantiate the...
0
8290
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
8707
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
8482
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
8593
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...
1
6161
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
5622
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
4149
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
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1593
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.