I used to have the following code to collect all (old style) class
names defined in the current module to a list called reg:
def meta( reg ):
def _meta( name, bases, dictionary ):
reg.append( name )
return _meta
reg = [ ]
__metaclass__ = meta( reg )
class c1:
pass
class c2:
pass
print reg
This would correctly print [ 'c1', 'c2' ]. Now I would like to switch
to new style classes but replacing class c1: and class c2: by class
c1(object): and class c2(object): doesn't work because the metaclass
associated with object will be called and not mine. Of course if I
would add __metaclass__ = meta(reg) to all class definitions that
would work, but how do I do this on the module level? 3 1496
On 16 dic, 14:44, "Daniel Nogradi" <nogr...@gmail. comwrote:
I used to have the following code to collect all (old style) class
names defined in the current module to a list called reg:
def meta( reg ):
def _meta( name, bases, dictionary ):
reg.append( name )
return _meta
reg = [ ]
__metaclass__ = meta( reg )
class c1:
pass
class c2:
pass
print reg
This would correctly print [ 'c1', 'c2' ]. Now I would like to switch
to new style classes but replacing class c1: and class c2: by class
c1(object): and class c2(object): doesn't work because the metaclass
associated with object will be called and not mine. Of course if I
would add __metaclass__ = meta(reg) to all class definitions that
would work, but how do I do this on the module level?
That code doesn't work even for classic classes. Anyway, you don't have
to add __metaclass__ everywhere, only to the base class(es).
If all you want to register is contained in a single module, I prefer a
function that iterates over all defined classes:
from inspect import isclass
for obj in globals().value s():
if isclass(obj): # may be stricter too, like issubclass(obj, Base)
reg.append(obj)
--
Gabriel Genellina
Daniel Nogradi wrote:
I used to have the following code to collect all (old style) class
names defined in the current module to a list called reg:
def meta( reg ):
def _meta( name, bases, dictionary ):
reg.append( name )
return _meta
reg = [ ]
__metaclass__ = meta( reg )
class c1:
pass
class c2:
pass
print reg
That code does not create classes. Here's a slightly simplified version:
>reg = []
>>def __metaclass__(n ame, bases, dict):
.... reg.append(name )
....
>>class A: pass
....
>>reg
['A']
>>A is None
True # oops!
This would correctly print [ 'c1', 'c2' ]. Now I would like to switch
to new style classes but replacing class c1: and class c2: by class
c1(object): and class c2(object): doesn't work because the metaclass
associated with object will be called and not mine. Of course if I
would add __metaclass__ = meta(reg) to all class definitions that
would work, but how do I do this on the module level?
If present, __metaclass__ serves as a factory for classes without an
explicit base class. For example,
__metaclass__ = type
would turn c1 and c2 into newstyle classes (that inherit from object).
If you want side effects you can wrap the metaclass into a function:
>>reg = [] def __metaclass__(n ame, bases, dict):
.... reg.append(name )
.... return type(name, bases, dict)
....
>>class A: pass
....
>>class B: pass
....
>>reg
['A', 'B']
>>issubclass( A, object)
True
Peter
I used to have the following code to collect all (old style) class
names defined in the current module to a list called reg:
def meta( reg ):
def _meta( name, bases, dictionary ):
reg.append( name )
return _meta
reg = [ ]
__metaclass__ = meta( reg )
class c1:
pass
class c2:
pass
print reg
That code does not create classes. Here's a slightly simplified version:
reg = [] def __metaclass__(n ame, bases, dict):
... reg.append(name )
...
>class A: pass
...
>reg
['A']
>A is None
True # oops!
This would correctly print [ 'c1', 'c2' ]. Now I would like to switch
to new style classes but replacing class c1: and class c2: by class
c1(object): and class c2(object): doesn't work because the metaclass
associated with object will be called and not mine. Of course if I
would add __metaclass__ = meta(reg) to all class definitions that
would work, but how do I do this on the module level?
If present, __metaclass__ serves as a factory for classes without an
explicit base class. For example,
__metaclass__ = type
would turn c1 and c2 into newstyle classes (that inherit from object).
If you want side effects you can wrap the metaclass into a function:
>reg = [] def __metaclass__(n ame, bases, dict):
... reg.append(name )
... return type(name, bases, dict)
...
>class A: pass
...
>class B: pass
...
>reg
['A', 'B']
>issubclass(A , object)
True
Thanks a lot, and sorry for the copy-paste error, I had the 'return
type(...)' line but didn't know that this already creates new-style
classes. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: zipher |
last post by:
After searching through comp.lang.python and the web regarding
metaclasses, I could not find an example for customing classes using
metaclass parameters.
I want to be able to create a class at runtime by calling some
function or 'meta-constructor' which returns a customized class and
sets a class attribute according a given parameter.
Ideally, I'd be able to do something like:
|
by: dody suria wijaya |
last post by:
I found this problem when trying to split a module into two.
Here's an example:
==============
#Module a (a.py):
from b import *
class Main: pass
==============
==============
|
by: Pedro Werneck |
last post by:
Hi
I have a class A, with metaclass M_A, and class B, subclass of A, with
metaclass M_B, subclass of M_A.
A class C, subclass of B must have M_B or a subclass of it as metaclass,
but what if I need to 'disable' the code in M_B on C ? The correct way
to do that seems to be with a M_C metaclass, subclass of M_B,
implementing but not calling parent class methods, or calling 'type'
methods.
|
by: RayS |
last post by:
I've begun a Python module to provide a complete interface to the
Meade LX200 command set, and have searched for a style/development
guide for Python Lib/site-packages type modules, but only saw guides
for C-modules. I realize that I need to make some changes to follow
http://www.python.org/doc/essays/styleguide.html
better. Does anyone have an appropriate URL for me to follow for this
task? Is one of the C-module guides appropriate?
I...
|
by: Pedro Werneck |
last post by:
Hi all
I noticed something strange here while explaining decorators to someone.
Not any real use code, but I think it's worth mentioning.
When I access a class attribute, on a class with a custom metaclass with
a __getattribute__ method, the method is used when acessing some
attribute directly with the class object, but not when you do it from
the instance.
| |
by: emin.shopper |
last post by:
I had a need recently to check if my subclasses properly implemented
the desired interface and wished that I could use something like an
abstract base class in python. After reading up on metaclass magic, I
wrote the following module. It is mainly useful as a light weight tool
to help programmers catch mistakes at definition time (e.g., forgetting
to implement a method required by the given interface). This is handy
when unit tests or...
|
by: Ramashish Baranwal |
last post by:
Hi,
I want to get a module's contents (classes, functions and variables)
in the order in which they are declared. Using dir(module) therefore
doesn't work for me as it returns a list in alphabetical order. As an
example-
# mymodule.py
class B: pass
class A: pass
|
by: Jens Thiede |
last post by:
I don't like the property function, usable in the new-style classes,
because having to remember to manage a list of "foo = property(...)"
assignments just plain sucks, so I wrote a metaclass that does things
a little differently. Please have a look and tell me whether this is
useful or impractical. The metaclass is here: http://pastebin.com/m5b06b571
and some simple testcode is here: http://pastebin.com/m382f2ae9.
Notice the first line...
|
by: thomas.karolski |
last post by:
Hi,
I would like to create a Decorator metaclass, which automatically
turns a class which inherits from the "Decorator" type into a
decorator.
A decorator in this case, is simply a class which has all of its
decorator implementation inside a decorator() method. Every other
attribute access is being proxied to decorator().getParent().
Here's my attempt:
-------------------------------------------------------
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |