Okay does anyone know how to decorate class member functions?
The following code gives me an error:
Traceback (most recent call last):
File "decorators2.py ", line 33, in <module>
s.update()
File "decorators2.py ", line 13, in __call__
retval = self.fn.__call_ _(*args,**kws)
TypeError: update() takes exactly 1 argument (0 given)
------------------
#! /usr/bin/env python
class Bugger (object):
def __init__ (self, module, fn):
self.module = module
self.fn = fn
def __call__ (self,*args, **kws):
ret_val = self.fn(*args,* *kws)
return ret_val
def instrument (module_name):
ret_val = lambda x: Bugger(module_n ame, x)
return ret_val
class Stupid:
def __init__(self):
self.val = 1
@instrument("xp d.spam")
def update(self):
self.val += 1
s = Stupid()
s.update() 12 4099
Oh I should mention the decorator needs to have some notion of state
(such as with the above class)
On May 3, 9:21 pm, Andy Terrel <andy.ter...@gm ail.comwrote:
Okay does anyone know how to decorate class member functions?
The following code gives me an error:
Traceback (most recent call last):
File "decorators2.py ", line 33, in <module>
s.update()
File "decorators2.py ", line 13, in __call__
retval = self.fn.__call_ _(*args,**kws)
TypeError: update() takes exactly 1 argument (0 given)
------------------
#! /usr/bin/env python
class Bugger (object):
def __init__ (self, module, fn):
self.module = module
self.fn = fn
def __call__ (self,*args, **kws):
ret_val = self.fn(*args,* *kws)
return ret_val
def instrument (module_name):
ret_val = lambda x: Bugger(module_n ame, x)
return ret_val
class Stupid:
def __init__(self):
self.val = 1
@instrument("xp d.spam")
def update(self):
self.val += 1
s = Stupid()
s.update()
A decorator is a function that takes one single parameter: a function.
"instrument " must return a decorator.
On May 3, 9:33 pm, Virgil Dupras <hardcoded.soft w...@gmail.comw rote:
On May 3, 9:21 pm, Andy Terrel <andy.ter...@gm ail.comwrote:
Okay does anyone know how to decorate class member functions?
The following code gives me an error:
Traceback (most recent call last):
File "decorators2.py ", line 33, in <module>
s.update()
File "decorators2.py ", line 13, in __call__
retval = self.fn.__call_ _(*args,**kws)
TypeError: update() takes exactly 1 argument (0 given)
------------------
#! /usr/bin/env python
class Bugger (object):
def __init__ (self, module, fn):
self.module = module
self.fn = fn
def __call__ (self,*args, **kws):
ret_val = self.fn(*args,* *kws)
return ret_val
def instrument (module_name):
ret_val = lambda x: Bugger(module_n ame, x)
return ret_val
class Stupid:
def __init__(self):
self.val = 1
@instrument("xp d.spam")
def update(self):
self.val += 1
s = Stupid()
s.update()
A decorator is a function that takes one single parameter: a function.
"instrument " must return a decorator.
Oh wait, I just embarrassed myself. Nevermind my last post.
On May 3, 9:21 pm, Andy Terrel <andy.ter...@gm ail.comwrote:
Okay does anyone know how to decorate class member functions?
The following code gives me an error:
Traceback (most recent call last):
File "decorators2.py ", line 33, in <module>
s.update()
File "decorators2.py ", line 13, in __call__
retval = self.fn.__call_ _(*args,**kws)
TypeError: update() takes exactly 1 argument (0 given)
------------------
#! /usr/bin/env python
class Bugger (object):
def __init__ (self, module, fn):
self.module = module
self.fn = fn
def __call__ (self,*args, **kws):
ret_val = self.fn(*args,* *kws)
return ret_val
def instrument (module_name):
ret_val = lambda x: Bugger(module_n ame, x)
return ret_val
class Stupid:
def __init__(self):
self.val = 1
@instrument("xp d.spam")
def update(self):
self.val += 1
s = Stupid()
s.update()
Second attempt. After some fuss around, I think it's just not possible
to have a class instance as a decorator. the self gets lost in
translation.
#! /usr/bin/env python
class Caller(object):
def __init__ (self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
print 'Caller calling!', repr(args)
return self.fn(*args, **kwargs)
def mydecorator(f):
return Caller(f)
class Stupid:
def __init__(self):
self.val = 1
@mydecorator
def update(self):
self.val += 1
s = Stupid()
s.update()
Caller calling! ()
Traceback (most recent call last):
File "/Users/hsoft/Desktop/foo.py", line 22, in ?
s.update()
File "/Users/hsoft/Desktop/foo.py", line 8, in __call__
return self.fn(*args, **kwargs)
TypeError: update() takes exactly 1 argument (0 given)
But why do you want to use a class? If you want to have a decorator
with argument, you only need to have something like:
def instrument(modu le):
def decorator(f):
def wrapper(*args, **kwargs):
print module
return f(*args, **kwargs)
return wrapper
return decorator
I just need to keep the state around. I make a call to some function
that is pretty expensive so I want to save it as a member during the
__init__ of the decorator.
Yeah I'm afraid it can't be done either, that's why I asked the group.
Andy Terrel <an*********@gm ail.comwrites:
I just need to keep the state around. I make a call to some function
that is pretty expensive so I want to save it as a member during the
__init__ of the decorator.
Yeah I'm afraid it can't be done either, that's why I asked the group.
Have you looked at memoize decorators? They seem to do what you want.
There are examples at the Python website (some link in there, I'm
sorry...).
This will give you lots of resources, including full recipes and
comments from the Python cookbook: http://www.google.com.br/search?q=py...orator+memoize
--
Jorge Godoy <jg****@gmail.c om>
not quite as elegant but here is a workaround... Thanks Virgil for
taking some time to think about it.
---
class Bugger (object):
def __init__ (self, module):
print "Entering __init__"
self.module = module
self.verb = 0
def instrument (module_name):
def wrapper(f):
def _wrap(*args,**k ws):
ret_val = f(*args,**kws)
return ret_val
return _wrap
b = Bugger(module_n ame)
if b.verb == 0:
ret_val = wrapper
else:
ret_val = lambda x:x
return ret_val
class Stupid:
def __init__(self):
self.val = 1
@instrument("sp am")
def update(self):
self.val += 1
s = Stupid()
s.update()
s.update()
s.update()
s.update()
print s.val
On Thu, 03 May 2007 19:28:52 -0700, Andy Terrel wrote:
I just need to keep the state around. I make a call to some function
that is pretty expensive so I want to save it as a member during the
__init__ of the decorator.
Yeah I'm afraid it can't be done either, that's why I asked the group.
You can do it if you give up on using the decorator syntax.
(Now that I've said that, some clever bunny will show me how to do it.)
def make_decorator( n):
def addspam(fn):
def new(*args):
print "spam " * n
return fn(*args)
return new
return addspam
class Parrot(object):
def __init__(self, count=3):
from new import instancemethod as im
self.describe = im(make_decorat or(count)(self. __class__.descr ibe), self)
def describe(self):
return "It has beautiful plummage."
>>bird = Parrot() bird.describe ()
spam spam spam
'It has beautiful plummage.'
>>>
bird = Parrot(5) bird.describe ()
spam spam spam spam spam
'It has beautiful plummage.'
--
Steven D'Aprano
Andy Terrel wrote:
Okay does anyone know how to decorate class member functions?
The following code gives me an error:
Traceback (most recent call last):
File "decorators2.py ", line 33, in <module>
s.update()
File "decorators2.py ", line 13, in __call__
retval = self.fn.__call_ _(*args,**kws)
TypeError: update() takes exactly 1 argument (0 given)
------------------
#! /usr/bin/env python
class Bugger (object):
def __init__ (self, module, fn):
self.module = module
self.fn = fn
def __call__ (self,*args, **kws):
ret_val = self.fn(*args,* *kws)
return ret_val
def instrument (module_name):
ret_val = lambda x: Bugger(module_n ame, x)
return ret_val
class Stupid:
def __init__(self):
self.val = 1
@instrument("xp d.spam")
def update(self):
self.val += 1
s = Stupid()
s.update()
The problem is not that you are decorating a method but that you are trying
to use a callable class instance as a method. For that to work the class
has to implement the descriptor protocol, see http://users.rcn.com/python/download/Descriptor.htm
class Bugger (object):
def __init__ (self, module, fn, instance=None):
self.module = module
self.fn = fn
self.instance = instance
def __call__ (self, *args, **kws):
print "calling %s.%s()" % (self.module, self.fn.__name_ _)
if self.instance is not None:
args = (self.instance, ) + args
ret_val = self.fn(*args, **kws)
return ret_val
def __get__(self, instance, class_):
if instance is None:
return self
return Bugger(self.mod ule, self.fn, instance)
def instrument (module_name):
ret_val = lambda x: Bugger(module_n ame, x)
return ret_val
class Stupid(object):
@instrument("xp d.spam")
def update(self):
print "update()"
s = Stupid()
s.update()
Stupid.update(s )
Peter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Roger Leigh |
last post by:
The C++ book I have to hand (Liberty and Horvath, Teach yourself C++
for Linux in 21 Days--I know there are better) states that "static
member functions cannot access any non-static member variables".
However, this doesn't seem entirely correct. It also doesn't mention
whether static member functions can access protected and private
member data and methods (and I couldn't spot this in the FAQ).
I have a class row<Row> which derives from...
|
by: surrealtrauma |
last post by:
i have a trouble about that:
i want to ask user to enter the employee data (employee no., name, worked
hour, etc.), but i dont know how to sort the data related to a particular
employee as a group. i want to use a array object in the class but i don't
know how..i am just learning the c++. So i dont know how to use class. in
fact, i have writen like the following:
class employee {
public:
employee();
|
by: gustav04 |
last post by:
hi all
i have a question:
what is the difference between a c-function and an c++ class method
(both do exactly the same thing).
lets say, i have a function called print2std() and a class called CUtils
with a static method called print2std()
|
by: yyy |
last post by:
my question is rather theoretical than practical in the pure programming
aspect...
is "name mangling" the same as "name decorating" ?
browsing the web, you might find multiple people saying "yes", but i
vaguely remember having read that it's not exactly like that
one might say that "name mangling" is a part of c++ compiler specification
and is a naming scheme to support function overloading
|
by: Sacha |
last post by:
I work on a rather large C++ project. The design, so far, seems to be
fine. However, there is one class, where the number of methods (and less
dramtically the number of members, too) is growing and growing. I
thought of different strategies to divert the glut into 'different
functional units', like
* through inheritance
* using member objects to encapsulate the methods of the parent object
* split the class without a parent class
*...
| |
by: kuvpatel |
last post by:
Hi
I want to refer a class called LogEvent, and use one of its methods called
WriteMessage without actually having to create an instance of Logevent.
I have tried using the word sealed with the class and this works but I would
also like to know of other ways to do this.
Also are there any performance implacations of using sealed?
|
by: davydany |
last post by:
Hey guys...a n00b Here for this site.
I'm making a sequence class for my C++ class. And The thing is in the array that I have, lets say i put in {13,17,38,18}, when i see the current values for the array data from 0 to3, I get this {13, JUNK VALUE, 17,38, 18} and JUNK VALUE is like 1.8e831 or something like that.
This happens when I use the attach() function and use the current() function to display the values at data
I really want to...
|
by: hardieca |
last post by:
Hi!
I decorate my unfinished classes and methods with a custom TODO
attribute (as in things To Do). Using reflection, I am then able to
parse through my classes and output all TODOs to a list I can examine
to figure out what is left to be done in my application.
The attribute is coded thusly:
AttributeUsage((AttributeTargets.Class | AttributeTargets.Method),
|
by: 1x7y2z9 |
last post by:
Say, we have a (parent) class P.
It has N child classes C1(P), C2(P) ... CN(P)
Each of the child classes defines (differently) a method func().
I wish to decorate all of the CX.func() in the same way. One way to
do this is to add a decorator to each of the derived classes. But
this is tedious and involves modifying multiple files.
Is there a way to modify the parent class and have the same effect?
|
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: 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...
|
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...
|
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: 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...
| |
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...
| |