473,698 Members | 2,528 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

metaclasses (beginner question)


Hello,

I would like to create a hierarchy classes, where the leaves have a
special attribute called "producer_i d". In addition, I would like to
have a function that can give me back the class assigned to any
producer_id value. I tried to implement this with a metaclass, but I
failed. Please help me, what I did wrong?

Thanks,

Laszlo
class ProducerHandler Type(type):
producer_handle rs = {}
@classmethod
def registerProduce rHandler(cls,pr oducer_id):
ph = cls.producer_ha ndlers
if ph.has_key(prod ucer_id):
ccls = ph[producer_id]
raise Exception("This producer already has a calculator:
"+str(ccls) )
else:
print "Registerin g "+str(cls)+ " for producer_id=",p roducer_id
ph[producer_id] = cls

def __init__(cls,na me,bases,dct):
super(ProducerH andlerType,cls) .__init__(cls,n ame,bases,dct)
if hasattr(cls,'pr oducer_id'):
cls.registerPro ducerHandler(ge tattr(cls,'prod ucer_id'))
else:
print "No producer_id for ",str(cls)
class A(ProducerHandl erType):
pass

class B(A):
producer_id = 1

class C(A):
producer_id = 2

# Metaclass methods are not called above, and the line below prints an
empty dict. :-(
print B.producer_hand lers
Feb 21 '07 #1
4 871
Laszlo Nagy wrote:
I would like to create a hierarchy classes, where the leaves have a
special attribute called "producer_i d". In addition, I would like to
have a function that can give me back the class assigned to any
producer_id value. I tried to implement this with a metaclass, but I
failed. Please help me, what I did wrong?
class ProducerHandler Type(type):
...
class A(ProducerHandl erType):
pass

class B(A):
producer_id = 1
# Metaclass methods are not called above, and the line below prints an
empty dict. :-(
Without looking into the details -- the (subclass of) type is meant to be
the class of the class, or the other way round, your normal classes are
instances of (a subclass of) type. You determine the factory Python uses to
make a class by adding

__metaclass__ = factory

to the class body, so you'll probably end with something like

class ProducerHandler Type(type):
# your code

class A:
__metaclass__ = ProducerHandler Type

The subclasses of A will now your invoke customised metaclass machinery.

Peter
Feb 21 '07 #2
Laszlo Nagy wrote:
I would like to create a hierarchy classes, where the leaves have a
special attribute called "producer_i d". In addition, I would like to
have a function that can give me back the class assigned to any
producer_id value. I tried to implement this with a metaclass, but I
failed. Please help me, what I did wrong?
class ProducerHandler Type(type):
...
class A(ProducerHandl erType):
pass

class B(A):
producer_id = 1
# Metaclass methods are not called above, and the line below prints an
empty dict. :-(
Without looking into the details -- the (subclass of) type is meant to be
the class of the class, or the other way round, your normal classes are
instances of (a subclass of) type. You determine the factory Python uses to
make a class by adding

__metaclass__ = factory

to the class body, so you'll probably end with something like

class ProducerHandler Type(type):
# your code

class A:
__metaclass__ = ProducerHandler Type

The subclasses of A will now invoke your customised metaclass machinery.

Peter
Feb 21 '07 #3
Without looking into the details -- the (subclass of) type is meant to be
the class of the class, or the other way round, your normal classes are
instances of (a subclass of) type. You determine the factory Python uses to
make a class by adding

__metaclass__ = factory

to the class body, so you'll probably end with something like

class ProducerHandler Type(type):
# your code

class A:
__metaclass__ = ProducerHandler Type

The subclasses of A will now invoke your customised metaclass machinery.
Thanks, I missed that. I added the __metaclass__ line and it worked like
a charm.

Laszlo

Feb 21 '07 #4
Peter Otten wrote:
You determine the factory Python uses to
make a class by adding

__metaclass__ = factory

to the class body, so you'll probably end with something like

class ProducerHandler Type(type):
# your code

class A:
__metaclass__ = ProducerHandler Type

The subclasses of A will now invoke your customised metaclass machinery.
This is the most perfectly succinct description of the __metaclass__
attribute I have ever seen. Beautiful.

James
Feb 22 '07 #5

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

Similar topics

2
1908
by: Stephan Diehl | last post by:
I have a question about metaclasses: How would be the best way to "merge" different metaclasses? Or, more precisely, what is the best way to merge metaclass functionality? The idea is basicly the following: One has several (metaclass) modules that implements an interesting feature. Lets say, I have a metaclass L, that adds logging capabilities to all method calls and another one, called P, that creates properties on the fly.
5
1458
by: Simon Burton | last post by:
It seems this is a more general way to build classes than inheritance. Is this a reasonable viewpoint? >>> >>> def meth1(self): .... print "i am meth1" .... >>> def meth2(self): .... print "i am meth2" ....
3
2092
by: Mike C. Fletcher | last post by:
Slides from my PyGTA presentation on Tuesday, focusing mostly on why/where you would want to use meta-classes, are available in PDF format: http://members.rogers.com/mcfletch/programming/metaclasses.pdf BTW, for those not on Python-list, be sure to check out David & Michele's newest developerworks article on the topic: http://www.ibm.com/developerworks/library/l-pymeta.html...
27
2004
by: Michele Simionato | last post by:
> Hello, my name is Skip and I am metaclass-unaware. I've been programming in > Python for about ten years and I have yet to write a metaclass. At first I > thought it was just that metaclasses were new to the language, but now as > more and more people use them and proclaim their widespread benefits, I have > come to realize that through years of abuse my brain has become addicted to > classic classes. I began using Python since...
4
2065
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...
13
1709
by: Jean-François Doyon | last post by:
Hello, I'm using MetaClasses to create classes. How do I make these new classes "globally" available? I probably just have to assign them to something magic, but I can't seem to figure out which one. if I do:
2
1545
by: Paul Morrow | last post by:
....that they warrant an entirely new syntax? It seems that they are very similar in a very significant way --- they alter the default behavior of something. IMO, it's not a stretch to say that they 'parallel' metaclasses; that they are to functions/methods what metaclasses are to classes. So why don't they share a similar syntax? class Foo: """ This is the docstring for class Foo. """ __metaclass__ = M # body of class goes here
9
1194
by: Steffen Glückselig | last post by:
Hello, I've been experimenting with metaclasses a bit (even though I am quite a newbie to python) and stumpled over the following problem in my code: class Meta(type): def __init__(cls, name, bases, dct): for attr, value in dct.items(): if callable(value): dct = wrapper(value)
0
1094
by: Jan-Ole Esleben | last post by:
Hi! I've just posted a question about metaclasses in ZOPE on the ZOPE list, and one of the replies said that metaclasses (at least "painless" metaclasses) cannot be used without new-style classes (or rather, that they don't work where you cannot explicitly use new-style classes). I haven't so far been able to find _anything_ on the subject - what is true here? TIA,
1
2506
by: Alan Isaac | last post by:
Forman's book is out of print. Is there a good substitute? Thanks, Alan Isaac
0
8678
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
8609
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
9166
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...
0
9030
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
8899
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
5861
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
4371
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
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2333
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.