473,606 Members | 2,877 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Play with classes

Hi to all!

I wonder if it possible (i'm sure python can do :-) ) to define classes on
runtime. My problem (schematically) is the folowwin.

The User can choise betwenn 3 property of an object.

Mode, Type and Subtype.

I have the following classes defined

ModeA, ModeB, TypeA, TypeB, TypeC, SubtypeA, SubtypeB.

Supose the user whant to combine ModeA with TypeB and SubtypeB, so I need
something like

class UserClass(ModeA , TypeB, SubtypeB):
pass

I can define all the posibilitys different classes and the using nested
if/else I can use the correct class, but I want to know if there is a way
generate in the fly and in this way there is no necesarity to change code whe
new Modes or Types are created.

I hope it is clear enough :-)

Thanks in advance

Zunbeltz
Jul 18 '05 #1
9 1506
Zunbeltz Izaola wrote:
Hi to all!

I wonder if it possible (i'm sure python can do :-) ) to define classes on
runtime. My problem (schematically) is the folowwin.

The User can choise betwenn 3 property of an object.

Mode, Type and Subtype.

I have the following classes defined

ModeA, ModeB, TypeA, TypeB, TypeC, SubtypeA, SubtypeB.

Supose the user whant to combine ModeA with TypeB and SubtypeB, so I need
something like

class UserClass(ModeA , TypeB, SubtypeB):
pass

I can define all the posibilitys different classes and the using nested
if/else I can use the correct class, but I want to know if there is a way
generate in the fly and in this way there is no necesarity to change code
whe new Modes or Types are created.

I hope it is clear enough :-)

Thanks in advance

Zunbeltz


How about assigning to __bases__?
class A: .... def alpha(self): print "alpha"
.... class B: .... def beta(self): print "beta"
.... class C: pass .... C.__bases__ () C.__bases__ = (A,B)
c = C()
c.alpha() alpha c.beta() beta
Trying the same thing with newstyle class resulted in a TypeError:
E.__bases__ = (A, B)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __bases__ assignment: 'A' deallocator differs from 'object'

Peter

Jul 18 '05 #2
Zunbeltz Izaola <zu******@wm.lc .ehu.es.XXX> writes:
I have the following classes defined

ModeA, ModeB, TypeA, TypeB, TypeC, SubtypeA, SubtypeB.

Supose the user whant to combine ModeA with TypeB and SubtypeB, so I need
something like

class UserClass(ModeA , TypeB, SubtypeB):
pass

I can define all the posibilitys different classes and the using nested
if/else I can use the correct class, but I want to know if there is a way
generate in the fly and in this way there is no necesarity to change code whe
new Modes or Types are created.


Is the following what you want ?

=============== =============== =============== =========
class TypeA: pass
class TypeB: pass
class TypeC: pass
class SubtypeA: pass
class SubtypeB: pass

collect_bases = [(Mode, Type, Subtype)
for Mode in [ModeA, ModeB]
for Type in [TypeA, TypeB, TypeC]
for Subtype in [SubtypeA, SubtypeB]]

count = 0
for bases in collect_bases:
name = "UserClass% d" % count
the_class = type(name, bases, {})
globals()[name] = the_class
count += 1
=============== =============== =============== =========

Now you can try
UserClass0.__ba ses__ (<class '__main__.ModeA '>, <class '__main__.TypeA '>, <class
'__main__.Subty peA'>)
UserClass1.__ba ses__ (<class '__main__.ModeA '>, <class '__main__.TypeA '>, <class
'__main__.Subty peB'>) UserClass2.__ba ses__ (<class '__main__.ModeA '>, <class '__main__.TypeB '>, <class
'__main__.Subty peA'>)

And so on, until
UserClass11.__b ases__

(<class '__main__.ModeB '>, <class '__main__.TypeC '>, <class
'__main__.Subty peB'>)
Jul 18 '05 #3
Jacek Generowicz <ja************ **@cern.ch> writes:
=============== =============== =============== =========
class TypeA: pass
class TypeB: pass
class TypeC: pass
class SubtypeA: pass
class SubtypeB: pass

collect_bases = [(Mode, Type, Subtype)
for Mode in [ModeA, ModeB]
for Type in [TypeA, TypeB, TypeC]
for Subtype in [SubtypeA, SubtypeB]]

count = 0
for bases in collect_bases:
name = "UserClass% d" % count
the_class = type(name, bases, {})
globals()[name] = the_class
count += 1
=============== =============== =============== =========


Oooops, the first 4 lines got lost:

=============== =============== =============== =========
__metaclass__ = type

class ModeA: pass
class ModeB: pass
class TypeA: pass
class TypeB: pass
class TypeC: pass
class SubtypeA: pass
class SubtypeB: pass

collect_bases = [(Mode, Type, Subtype)
for Mode in [ModeA, ModeB]
for Type in [TypeA, TypeB, TypeC]
for Subtype in [SubtypeA, SubtypeB]]

count = 0
for bases in collect_bases:
name = "UserClass% d" % count
globals()[name] = type(name, bases, {})
count += 1
=============== =============== =============== =========
Jul 18 '05 #4
Jacek Generowicz <ja************ **@cern.ch> writes:

Thank for the help.

Oooops, the first 4 lines got lost:

=============== =============== =============== =========
__metaclass__ = type

I am not an expert and i don't understand very well things like
__metaclass__, but it not redundat this line? From the Language Reference

"""
__metaclass__
This variable can be any callable accepting arguments for name, bases,
and dict. Upon class creation, the callable is used instead of the
built-in type(). New in version 2.2.
"""

so I think __metaclass__ = type is the same as not defining __metaclass__

Regards,

Zunbeltz
class ModeA: pass
class ModeB: pass
class TypeA: pass
class TypeB: pass
class TypeC: pass
class SubtypeA: pass
class SubtypeB: pass

collect_bases = [(Mode, Type, Subtype)
for Mode in [ModeA, ModeB]
for Type in [TypeA, TypeB, TypeC]
for Subtype in [SubtypeA, SubtypeB]]

count = 0
for bases in collect_bases:
name = "UserClass% d" % count
globals()[name] = type(name, bases, {})
count += 1
=============== =============== =============== =========

Jul 18 '05 #5

"Zunbeltz Izaola" <zu******@wm.lc .ehu.es.XXX> wrote in message
news:ct******** *****@lcpxdf.wm .lc.ehu.es...
Hi to all!

I wonder if it possible (i'm sure python can do :-) ) to define classes on runtime. My problem (schematically) is the folowwin.


The class statement, like all statements except the global directive, it a
runtime executable statement. So, in a sense, all class objects are
defined (created) at runtime. So you are perhaps asking, "Can I write a
class statement at runtime (using user input)?" If so, yes. Create a
string with the code you want executed, then exec it with an exec
statement. Or you can use the approach others suggested of interpreting
user input to build up a class object. Your choice.

Terry J. Reedy


Jul 18 '05 #6
Peter Otten <__*******@web. de> wrote in message news:<c1******* ******@news.t-online.com>...
Trying the same thing with newstyle class resulted in a TypeError:
E.__bases__ = (A, B)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __bases__ assignment: 'A' deallocator differs from 'object'


You can't do that with new style classes! I guess because of some
subtle issue with metaclasses, but I don't really know.

The OP needs "type", the custom metaclass:

UserClass=type( "UserClass",(Mo deA, TypeB, SubtypeB),{})
Michele Simionato
Jul 18 '05 #7
In article <ct************ *@lcpxdf.wm.lc. ehu.es>, Zunbeltz Izaola wrote:
Supose the user whant to combine ModeA with TypeB and SubtypeB, so I need
something like

class UserClass(ModeA , TypeB, SubtypeB):

You can use the type builtin (2.2 and above) to create a class type
dynamically. Syntax is

type(name_strin g, bases_tuple, methods_dict)

For example:

In [68]: foo = type('Foo', (object,), {})
In [69]: foo.mro()
Out[69]: [<class '__main__.Foo'> , <type 'object'>]

Dave Cook
Jul 18 '05 #8
As another poster noted, all classes are created at run-time. There's
even a hook that let's you intercept the creation of a class called the
"metaclass hook", however, to deal with the question directly before I
go off on a tangent...

There are two major approaches you can take to elegantly composing
classes at run-time; Factory functions and metaclasses. Here's an
example of the factory function approach, (which is probably most
appropriate in your case (user is only creating new classes via GUI
interactions, no need for ability to sub-class in Python code, no need
for addition of newly-created methods/functions, i.e. straight
composition)):

def createClass( name, baseClasses, dictionary ):
"""Create a new class object and return it"""
# reshuffle baseClasses here
# manipulate dictionary here
# check that name is unique here
# register with some global registry here
# register pickle helpers here
if definitions.has _key( uniqueFingerpri nt):
return that
else:
# if you were paying attention, you'll notice
# that save for the manipulation comments we
# just call this...
return type( name, baseClasses, dictionary )

If, however, your users may *also* want to define these classes as part
of Python modules (for an extension mechanism), you may want to subclass
"type" to encode your registration/reshuffling/manipulation/etc.
directly and then use that metaclass (sub-class of type) for each of
your classes:

class MetaFoo( type ):
"""Metaclas s for the example code"""
definitions = {}
def __new__( metacls, name, bases, dictionary ):
# reshuffle baseClasses here
# manipulate dictionary here
# check that name is unique here
uniqueFingerpri nt = name, bases
if metacls.definit ions.has_key( uniqueFingerpri nt ):
# Note: this likely *isn't* a good idea, as it can really
# surprise your users to discover that their classes
# are silently unified with another class! Just a demo...
return metacls.definit ions.get( uniqueFingerpri nt )
else:
result = super(MetaFoo,m etacls).__new__ (
metacls, name, bases, dictionary
)
metacls.definit ions[ uniqueFingerpri nt ] = result
# register with some global registry here
# register pickle helpers here
return result

__metaclass__ = MetaFoo
class ModeA:
pass

class ModeB:
pass

class ModeC( ModeA, ModeB ):
pass
class ModeD( ModeA, ModeB ):
pass

print MetaFoo( 'A', (), {} ) is MetaFoo( 'A', (), {} )

As noted in the comments above, likely you don't even want the effect of
having the class-cache (too confusing for users, mostly, but I wanted
some sort of manipulation to stick in to say "something happens here" :)
), so there's no particular value to the metaclass version for your
case. I just wanted an opportunity to work on an example for my talk...
I'm sick, I know...

Some things to keep in mind:

* Your new class instances will *not* be pickle-able (using either
method) unless they are registered explicitly somewhere in an
importable module. You will need to figure out how to ensure
that, on unpickling, your newly-created classes are available
(e.g. by storing their definitions in a database somewhere and
hooking import to treat the DB as a module).
* metaclasses are more fun :) , but they take some getting used to,
and are probably overkill for this simple excursion into
metaprogramming
* The "new" module has an (ironically) older API for creating class
objects

Have fun,
Mike

Zunbeltz Izaola wrote:
Hi to all!

I wonder if it possible (i'm sure python can do :-) ) to define classes on
runtime. My problem (schematically) is the folowwin.

The User can choise betwenn 3 property of an object.

Mode, Type and Subtype.

I have the following classes defined

ModeA, ModeB, TypeA, TypeB, TypeC, SubtypeA, SubtypeB.

Supose the user whant to combine ModeA with TypeB and SubtypeB, so I need
something like

class UserClass(ModeA , TypeB, SubtypeB):
pass

I can define all the posibilitys different classes and the using nested
if/else I can use the correct class, but I want to know if there is a way
generate in the fly and in this way there is no necesarity to change code whe
new Modes or Types are created.

....
Jul 18 '05 #9
Zunbeltz Izaola <zu******@wm.lc .ehu.es.XXX> writes:
Jacek Generowicz <ja************ **@cern.ch> writes:

Thank for the help.
I hope that it is what you were asking for.

Of course, my posting such a solution should in no way be interpreted
as a suggestion that it is appropriate to your _real_ problem. You may
well want a completely different approach, but I can't tell without
knowing more about your application.
__metaclass__ = type


I am not an expert and i don't understand very well things like
__metaclass__, but it not redundat this line? From the Language Reference

"""
__metaclass__
This variable can be any callable accepting arguments for name, bases,
and dict. Upon class creation, the callable is used instead of the
built-in type(). New in version 2.2.
"""

so I think __metaclass__ = type is the same as not defining __metaclass__


It is indeed tempting to conclude that from what you have quoted.

One of the beauties of Python is its highly interactive nature, and
the ease with which you can try things out. Your hypothesis that
"__metaclas s__ = type is the same as not defining __metaclass__" can
be refuted by the Python interpreter itself within about 10 seconds of
work. Take the code I sent, remove the binding of __metaclass__ and
run the code. You will find that Python replies:

TypeError: a new-style class can't have only classic bases

As written in my example, ("class ModeA: pass" etc.) all the classes
are classic, because they do not inherit from object.
class classic: pass .... class newstyle(object ): pass .... type(classic) <type 'class'> type(newstyle)

<type 'type'>

I want them to be new-style classes, because I am going to create new
classes which inherit from them, using type. This means of creating
classes creates new-style classes, and new style classes, as the error
message above suggests, "can't have only classic bases".

So, I could either make ModeA & co inherit from object, or I could
make all classes new-style ones by default, by binding __metaclass__
to type.

Alternatively, I could not use type to create the UserClasses, but
types.ClassType (types is a module). Alternatively I could use use
type(ModeA) which would pick the appropriate metaclass for creation of
your UserClasses depending on the situation.
"""
__metaclass__
This variable can be any callable accepting arguments for name, bases,
and dict. Upon class creation, the callable is used instead of the
built-in type(). New in version 2.2.
"""


Hmm. Is that a documentation bug? I suspect that it should read "
.... instead of types.ClassType "
[ So, here's a classic class version of the original:

class ModeA: pass
class ModeB: pass
class TypeA: pass
class TypeB: pass
class TypeC: pass
class SubtypeA: pass
class SubtypeB: pass

collect_bases = [(Mode, Type, Subtype)
for Mode in [ModeA, ModeB]
for Type in [TypeA, TypeB, TypeC]
for Subtype in [SubtypeA, SubtypeB]]

count = 0
for bases in collect_bases:
name = "UserClass% d" % count
globals()[name] = type(ModeA)(nam e, bases, {})
# or you could "import types" and do the following
# globals()[name] = types.ClassType (name, bases, {})
count += 1

]
Jul 18 '05 #10

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

Similar topics

0
972
by: Holger Joukl | last post by:
I have the following classes defined ModeA, ModeB, TypeA, TypeB, TypeC, SubtypeA, SubtypeB. Supose the user whant to combine ModeA with TypeB and SubtypeB, so I need something like class UserClass(ModeA, TypeB, SubtypeB): pass _________________________________
4
2053
by: Michael Sparks | last post by:
Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it looked like about 20:20 split on the following syntaxes: 1 def func(arg1, arg2, arg3) : function... 2 def func(arg1, arg2, arg3): function...
1
1343
by: Paul Rubin | last post by:
Just a slight rant, I think I can find a workaround. I wanted to trace all the output being sent through a socket: from socket import * sock = socket() socket.connect((host, post)) socket.send('hello over there\n') # I want to log the string Sounds like a job for new style classes:
22
2532
by: The Road To Utopia | last post by:
Here's one for the trolls...a common jibe from them is setting up audio/video hardware under linux. Ok, true story: at work today, someone asked me if I could tell him why his XP Home would play the video from a DVD but not the audio. He had been searching for an answer for days on support.microsoft.com but found none. I suggested Google and Gateway. Gateway had nothing, but sure enough, search for *XP DVD no sound* on Google and...
1
4288
by: Ron Provost | last post by:
Hello, I'm developing a piece of software to assist illiteraate adults to learn to read. I'm trying to figure out how, if possible, to make audio playback asynchrnous but still controllable. I'm using python 2.4 with pymedia on XP. I started out with the example in the tutorials section of the pymedia website. The pymedia docs imply to me that playback using Output's play() method should already be asynchronous and controllable. I...
5
3581
by: djc | last post by:
what choices do I have to play sounds in a program using vb.net? Or, I guess if nothing vb specific what windows API(s) should I look at? I am interested to find out whats needed for playing short wav files for sound effects as well as playing longer sound clips in mp3 format. can anyone point me in the right direction?
10
1941
by: sarayu | last post by:
Hi, I want to convert some video files to .flv format and store it in database and play.For this i used ffmpeg and i convert the files in cmd and here my problem is how can i connect ffmpeg and php.I searched for it but i got an error in ffmpeg-php classes.Which class is suitable for my application and how we connect with.Please help me?
6
2966
by: elizabeth1986 | last post by:
Hello, Is it possible to detect the insertion and removal of Plug and play devices (for example : keyboard , mouse etc) while the computer is still ON. We wanted to do the above in C#. We tried a couple of WMI classes like win32_Keyboard class, but after manually removing the Keyboard, there was no change in the Property "status" of win32_Keyboard. it showed that the status was OK. We also tried a...
6
1328
by: centenial | last post by:
Hi all, I have a PHP OOP design question. I've done some searching in google, but wasn't able to turn up anything concrete. I'm hoping some experts can point me to the most elegant solution. I have a set of classes. All of my classes "extend" an abstract class called Base. (This class reads a config file, has a basic set of common methods, and sets up needed parameters) Most of my classes need a class called Mysql to perform database...
0
8031
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
7962
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,...
1
8107
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
8315
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
5467
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
3945
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...
1
2452
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
1
1565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1309
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.