473,834 Members | 1,930 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

mixin class

Hi,

I try to implement mixin classes. Thats why I
need to make a new class at runtime.

--tmp.py-------------------------------------

import new

class K1(object):
pass

class K2(object):
pass

mixed = new.classobj("K 1_K2", (K1, K1), {})
new_instance = new.instance(mi xed, {})

print new_instance

---------------------------------------------

Making a new instance from the new class works
only if K1 is not derived from object. If I use
new style classes I get the following traceback:

Traceback (most recent call last):
File "tmp.py", line 10, in ?
new_instance = new.instance(mi xed, {})
TypeError: instance() argument 1 must be class, not type

I use Python 2.2.3 and Win2000.

My question: How do I implement mixin classes
with new style classes?

Thanks,

Udo

Jul 18 '05 #1
5 2740
Udo Gleich <ud********@web .de> wrote in message news:<3F******* ********@web.de >...
Hi,

I try to implement mixin classes. Thats why I
need to make a new class at runtime.

--tmp.py-------------------------------------

import new

class K1(object):
pass

class K2(object):
pass

mixed = new.classobj("K 1_K2", (K1, K1), {})
new_instance = new.instance(mi xed, {})

print new_instance

---------------------------------------------

Making a new instance from the new class works
only if K1 is not derived from object. If I use
new style classes I get the following traceback:

Traceback (most recent call last):
File "tmp.py", line 10, in ?
new_instance = new.instance(mi xed, {})
TypeError: instance() argument 1 must be class, not type

I use Python 2.2.3 and Win2000.

My question: How do I implement mixin classes
with new style classes?

Thanks,

Udo


Why not simply

class K1(object):
pass

class K2(object):
pass

mixed = type("K1_K2", (K1, K1), {})
new_instance = mixed()

print new_instance

?

"type" is described in http://www.python.org/2.2.3/descrintro.html
(in one line very easy to miss ;)
Michele
Jul 18 '05 #2
Hi,
Why not simply

class K1(object):
pass

class K2(object):
pass

mixed = type("K1_K2", (K1, K1), {})
new_instance = mixed()

print new_instance


almost.

If K1 has a constructor that takes arguments you get an
error when you call the constructor of the derived class
without an argument. Why do I want to do that? Usually
one would say that I should know the arguments of the
constructor of the derived class.

What I want to do is take *two objects*, derive from both
their classes, make a new object and combine the state of
the old objects.

I dont know if that is a good idea. I would appreciate comments
on the following solution. Especially the use of the dummy_init
function as an empty constructor looks not quite right to me.

---------------------------------------------------------------------

def dummy_init(self ):
pass

class Mixin:

__shared_state = {"classes":{ }}

def __init__(self):
self.__dict__ = self.__shared_s tate

def mix(self, original_instan ce, mixin_instance) :
original_class = original_instan ce.__class__
mixin_class = mixin_instance. __class__
name = original_class. __name__ + '_' + mixin_class.__n ame__
mixed = self.classes.ge t(name,
type(name,
(mixin_class, original_class) ,
{"__init__": dummy_init}))
new_instance = mixed()

new_instance.__ dict__.update(m ixin_instance._ _dict__)
new_instance.__ dict__.update(o riginal_instanc e.__dict__)

try:
new_instance.la te_init_origina l()
except AttributeError:
pass
try:
new_instance.la te_init_mixin()
except AttributeError:
pass
return new_instance

class K1(object):
def __init__(self, a):
self.a = a

class K2(object):
def late_init_mixin (self):
self.b = self.a + 1
mixer = Mixin()

new_instance = mixer.mix(K1(3) , K2())

print new_instance
print new_instance.a, new_instance.b

-------------------------------------------------------------------------
Jul 18 '05 #3
> > mixed = new.classobj("K 1_K2", (K1, K1), {})

There is an error in the code. Obviously it should
read

mixed = new.classobj("K 1_K2", (K1, K2), {})
--
Jul 18 '05 #4
Udo Gleich <ud********@web .de> wrote in message news:<3F******* ********@web.de >...
What I want to do is take *two objects*, derive from both
their classes, make a new object and combine the state of
the old objects.

I dont know if that is a good idea. I would appreciate comments
on the following solution. Especially the use of the dummy_init
function as an empty constructor looks not quite right to me.


You may avoid dummy_init and have the default object.__init__ but
this is not the point. The whole construction seems ugly to me.
Do you have the option of using only class variables ? I mean, no
explicit instance dictionary? Then you could simply create the
mixin from the original classes and not merge by hand the
instance dictionaries. Do you have the option of modifying the
original classes to make the all structure more multiple inheritance
friendly? The idea is that one should derive objects from classes,
not classes from objects. What you are doing will probably work,
but It is quite ugly to me.I cannot say more if I have no idea of what
are your constraints. If you cannot touch the original classes,
remember that you can create modifications of them, as mixin-frendly
as you wish. I also have a question: why don't you override the
__init__ method in M in such a way that it calls K1.__init__ and
K2.__init__ according to the number of arguments? That would be
the first thing would come to my mind, but maybe you have reasons
why you don't want that.
HTH,
Michele
Jul 18 '05 #5
On Mon, 28 Jul 2003 12:20:02 +0200, Udo Gleich wrote:
My question: How do I implement mixin classes
with new style classes?


Um, if I understand what you're trying to do correctly, it's easy:

--------------
import random

class A(object): pass
class B(object): pass
class C(object): pass
class D(object): pass

mixin = random.choice([C, D])

class A_B_and_C_or_D( A, B, mixin): pass

newName = A_B_and_C_or_D

newInstance = newName()
----------------

(Warning: Didn't actually type this in)

The classes being derived from can be variable; in fact I do this rather
too frequently for my own good, perhaps. (I tend to use it for class I
want to be intimately involved with each other, but also usable
separately, having one of them dynamically derive from either object or
the other class, depending on whether the other class is available.)

So in this example, on any given run, class A_B_and_C_or_D will always
derive from A and B, and may derive from either of C or D.

You can dynamically do this in a loop or something if you're feeling
creative, if you assign the class to new names, as I did here for
"newName". AFAIK there's no way to programmaticall y create new classes
with generated names without resorting to eval (bad idea), but you can
bind them to new names after creation and that works OK.

----------------

classesILike = {}
for i in range(10):
class tmp(object): pass
classesILIke[i] = tmp

----------------

and of course "tmp" may derive from what it will.

The inheritance list is as dynamic as anything else in Python; feel free
to use it that way. Personally I find this is a "killer feature"... you'd
find it hard to describe in advance when you'd want it, but when
you want it, you want it ***badly***, because the kludge will be a
killer... and there are very, very few languages that can do this cleanly
(and still share Python's other benefits).
Jul 18 '05 #6

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

Similar topics

0
1627
by: zimba | last post by:
Hello ! If somebody is interested, here is a small hack I've done today. There are still some curious effects, but I'm pretty satisfied by the results, since PHP is not very flexible. Let me know what you think, I'm looking into talking about somethin ;)
1
2584
by: Mac | last post by:
I have a MixIn class which defines a method foo(), and is then mixed in with another class by being prepended to that class's __bases__ member, thus overriding that class's definition of foo(). In my application though it is necessary for the MixIn's foo() to call the overridden foo(). How can I do this? My current hack is to do this: def foo(): # MixIn's method orig_bases = self.__class__.__bases__
0
1335
by: Paolino | last post by:
I had always been negative on the boldeness of python on insisting that unbound methods should have been applied only to its im_class instances. Anyway this time I mixed in rightly, so I post this for comments. ###### looking for a discovery .Start ################# class _Mixin(object): def __init__(self,main,instance,*args,**kwargs): # do mixin businnes main.__reinit__(self,instance) # the caveated interface
0
345
by: barnesc | last post by:
>So mixins are just a sub-class of sub-classing? > >I've just found this: > > >A mixin class is a parent class that is inherited from - but not as >a means of specialization. Typically, the mixin will export services to a >child class, but no semantics will be implied about the child "being a >kind of" the parent. >
6
2490
by: Alex Hunsley | last post by:
I know that I can catch access to unknown attributes with code something like the following: class example: def __getattr__(self, name): if name == 'age': return __age else: raise AttributeError
3
1482
by: Ed Leafe | last post by:
In Dabo, we create cursor classes that combine the backend-specific dbapi cursor class with our own mixin class that adds framework- specific behaviors. This has been working well for a couple of years now with many different backends, but today I'm getting errors with our Firebird class. I've checked the kinterbasdb site, and found nothing there that was helpful. The error reads: TypeError: Error when calling the metaclass bases type...
2
2211
by: ish | last post by:
I think this is more of a style question than anything else... I'm doing a C++ wrapper around a C event library I have and one of the items is a timer class, I'm also using this task to learn C++. Is it cleaner to have users subclass my Timer class and implement the on_timeout() method? Or should the user use a mixin and provide the mixin to my Timer class? The subclass method kinda looks like this..
1
1434
by: Ole Nielsby | last post by:
Given these 3 classes class A {virtual void a(){}}; class B {virtual void b(){}}; class C: public A, public B {}; I want the offset of B in C, as a size_t value, and preferably as a constant expression. I got a solution that seems to work on VC9Express:
2
1615
by: viboes | last post by:
Hello, Very often we need to name the basetype of a derived type class D : public B { typedef B base_type; // ... }; When B es a complexe template expression we need to repeat the
0
9799
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
10793
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10548
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
9331
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
6954
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
5794
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4427
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
2
3978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3081
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.