Search Results

Search found 206 results on 9 pages for 'decorator'.

Page 1/9 | 1 2 3 4 5 6 7 8 9  | Next Page >

  • Python decorator question

    - by nsharish
    decorator 1: def dec(f): def wrap(obj, *args, **kwargs): f(obj, *args,**kwargs) return wrap decorator 2: class dec: def __init__(self, f): self.f = f def __call__(self, obj, *args, **kwargs): self.f(obj, *args, **kwargs) A sample class, class Test: @dec def disp(self, *args, **kwargs): print(*args,**kwargs) The follwing code works with decorator 1 but not with decorator 2. a = Test() a.disp("Message") I dont understand why decorator 2 is not working here. Can someone help me with this?

    Read the article

  • python class decorator question?

    - by nsharish
    decorator 1: def dec(f): def wrap(obj, *args, **kwargs): f(obj, *args,**kwargs) return wrap decorator 2: class dec: def __init__(self, f): self.f = f def __call__(self, obj, *args, **kwargs): self.f(obj, *args, **kwargs) A sample class, class Test: @dec def disp(self, *args, **kwargs): print(*args,**kwargs) The follwing code works with decorator 1 but not with decorator 2. a = Test() a.disp("Message") I dont understand why decorator 2 is not working here. Can someone help me with this?

    Read the article

  • Refresh decorator

    - by Morgoth
    I'm trying to write a decorator that 'refreshes' after being called, but where the refreshing only occurs once after the last function exits. Here is an example: @auto_refresh def a(): print "In a" @auto_refresh def b(): print "In b" a() If a() is called, I want the refresh function to be run after exiting a(). If b() is called, I want the refresh function to be run after exiting b(), but not after a() when called by b(). Here is an example of a class that does this: class auto_refresh(object): def __init__(self, f): print "Initializing decorator" self.f = f def __call__(self, *args, **kwargs): print "Before function" if 'refresh' in kwargs: refresh = kwargs.pop('refresh') else: refresh = False self.f(*args, **kwargs) print "After function" if refresh: print "Refreshing" With this decorator, if I run b() print '---' b(refresh=True) print '---' b(refresh=False) I get the following output: Initializing decorator Initializing decorator Before function In b Before function In a After function After function --- Before function In b Before function In a After function After function Refreshing --- Before function In b Before function In a After function After function So when written this way, not specifying the refresh argument means that refresh is defaulted to False. Can anyone think of a way to change this so that refresh is True when not specified? Changing the refresh = False to refresh = True in the decorator does not work: Initializing decorator Initializing decorator Before function In b Before function In a After function Refreshing After function Refreshing --- Before function In b Before function In a After function Refreshing After function Refreshing --- Before function In b Before function In a After function Refreshing After function because refresh then gets called multiple times in the first and second case, and once in the last case (when it should be once in the first and second case, and not in the last case).

    Read the article

  • Observer pattern used with decorator pattern

    - by icelated
    I want to make a program that does an order entry system for beverages. ( i will probably do description, cost) I want to use the Decorator pattern and the observer pattern. I made a UML drawing and saved it as a pic for easy viewing. This site wont let me upload as a word doc so i have to upload a pic - i hope its easily viewable.... I need to know if i am doing the UML / design patterns correctly before moving on to the coding part. Beverage is my abstract component class. Espresso, houseblend, darkroast are my concrete subject classes.. I also have a condiment decorator class milk,mocha,soy,whip. would be my observer? because they would be interested in data changes to cost? Now, would the espresso,houseblend etc, be my SUBJECT and the condiments be my observer? My theory is that Cost is a changes and that the condiments need to know the changes? So, subject = esspresso,houseblend,darkroast,etc.. // they hold cost() Observer = milk,mocha,soy,whip? // they hold cost() would be the concrete components and the milk,mocha,soy,whip? would be the decorator! So, following good software engineering practices "design to an interface and not implementation" or "identify things that change from those that dont" would i need a costbehavior interface? If you look at the UML you will see where i am going with this and see if i am implementing observer + Decorator pattern correctly? I think the decorator is correct. since, the pic is not very viewable i will detail the classes here: Beverage class(register observer, remove observer, notify observer, description) these classes are the concrete beverage classes espresso, houseblend,darkroast, decaf(cost,getdescription,setcost,costchanged) interface observer class(update) // cost? interface costbehavior class(cost) // since this changes? condiment decorator class( getdescription) concrete classes that are linked to the 2 interface s and decorator are: milk,mocha,soy,whip(cost,getdescription,update) these are my decorator/ wrapper classes. Thank you.. Is there a way to make this picture bigger?

    Read the article

  • Flexible Decorator Pattern?

    - by Omar Kooheji
    I was looking for a pattern to model something I'm thinking of doing in a personal project and I was wondering if a modified version of the decorator patter would work. Basicly I'm thinking of creating a game where the characters attributes are modified by what items they have equiped. The way that the decorator stacks it's modifications is perfect for this, however I've never seen a decorator that allows you to drop intermediate decorators, which is what would happen when items are unequiped. Does anyone have experience using the decorator pattern in this way? Or am I barking up the wrong tree? Clarification To explain "Intermediate decorators" if for example my base class is coffe which is decorated with milk which is decorated with sugar (using the example in Head first design patterns) milk would be an intermediate decorator as it decorates the base coffee, and is decorated by the sugar. Yet More Clarification :) The idea is that items change stats, I'd agree that I am shoehorning the decorator into this. I'll look into the state bag. essentially I want a single point of call for the statistics and for them to go up/down when items are equiped/unequiped. I could just apply the modifiers to the characters stats on equiping and roll them back when unequiping. Or whenever a stat is asked for iterate through all the items and calculate the stat. I'm just looking for feedback here, I'm aware that I might be using a chainsaw where scissors would be more appropriate...

    Read the article

  • Question about decorator pattern and the abstract decorator class?

    - by es11
    This question was asked already here, but rather than answering the specific question, descriptions of how the decorator pattern works were given instead. I'd like to ask it again because the answer is not immediately evident to me just by reading how the decorator pattern works (I've read the wikipedia article and the section in the book Head First Design Patterns). Basically, I want to know why an abstract decorator class must be created which implements (or extends) some interface (or abstract class). Why can't all the new "decorated classes" simply implement (or extend) the base abstract object themselves (instead of extending the abstract decorator class)? To make this more concrete I'll use the example from the design patterns book dealing with coffee beverages: There is an abstract component class called Beverage Simple beverage types such as HouseBlend simply extend Beverage To decorate beverage, an abstract CondimentDecorator class is created which extends Beverage and has an instance of Beverage Say we want to add a "milk" condiment, a class Milk is created which extends CondimentDecorator I'd like to understand why we needed the CondimentDecorator class and why the class Milk couldn't have simply extended the Beverage class itself and been passed an instance of Beverage in its constructor. Hopefully this is clear...if not I'd simply like to know why is the abstract decorator class necessary for this pattern? Thanks. Edit: I tried to implement this, omitting the abstract decorator class, and it seems to still work. Is this abstract class present in all descriptions of this pattern simply because it provides a standard interface for all of the new decorated classes?

    Read the article

  • Is WPF Decorator class useful?

    - by darja
    I need to create control to draw border around its child. So, I have created class and derived it from Decorator: class RoundedBoxDecorator : Decorator { protected override Size ArrangeOverride(Size arrangeSize) { //some source } protected override void OnRender(DrawingContext dc) { //some source } } It works fine, but I have some doubts about using Decorator as ancestor. I have found in MSDN that there are no special methods or properties in it, only derived from its ancestors (UIElement or FrameworkElement). ArrangeOverride and OnRender are also derived. So, what for Decorator class was designed and does it makes sense to use it? Or I can derive from FrameworkElement?

    Read the article

  • A better python property decorator

    - by leChuck
    I've inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes all over the project. The problem is that this I have traced my debugging problems to this decorator. Seems it "fubars" all debuggers I've tried and trying to speed up the code with psyco breaks everthing. (Seems psyco and this decorator dont play nice). I think it would be best to change it. def Property(function): """Allow readable properties""" keys = 'fget', 'fset', 'fdel' func_locals = {'doc':function.__doc__} def probeFunc(frame, event, arg): if event == 'return': locals = frame.f_locals func_locals.update(dict((k,locals.get(k)) for k in keys)) sys.settrace(None) return probeFunc sys.settrace(probeFunc) function() return property(**func_locals) Used like so: class A(object): @Property def prop(): def fget(self): return self.__prop def fset(self, value): self.__prop = value ... ect The errors I get say the problems are because of sys.settrace. (Perhaps this is abuse of settrace ?) My question: Is the same decorator achievable without sys.settrace. If not I'm in for some heavy rewrites.

    Read the article

  • Is this a good decorator pattern for javascript?

    - by Kucebe
    I need some simple objects that could become more complex later, with many different properties, so i thought to decorator pattern. I made this looking at Crockford's power constructor and object augmentation: //add property to object Object.prototype.addProperty = function(name, func){ for(propertyName in this){ if(propertyName == name){ throw new Error(propertyName + " is already defined"); } } this[name] = func; }; //constructor of base object var BaseConstructor = function(param){ var _privateVar = param; return{ getPrivateVar: function(){ return _privateVar; } }; }; //a simple decorator, adds one private attribute and one privileged method var simpleDecorator = function(obj, param){ var _privateVar = param; var privilegedMethod1 = function(){ return "privateVar of decorator is: " + _privateVar; }; obj.addProperty("privilegedMethod1", privilegedMethod1); return obj; } //a more complex decorator, adds public and private properties var complexDecorator = function(obj, param1, param2){ //private properties var _privateVar = param1; var _privateMethod = function(x){ for(var i=0; i<x; i++){ _privateVar += x; } return _privateVar; }; //public properties var publicVar = "I'm public"; obj.addProperty("publicVar", publicVar); var privilegedMethod2 = function(){ return _privateMethod(param2); }; obj.addProperty("privilegedMethod2", privilegedMethod2); var publicMethod = function(){ var temp = this.privilegedMethod2(); return "do something: " + temp + " - publicVar is: " + this.publicVar; }; obj.addProperty("publicMethod", publicMethod); return obj; } //new basic object var myObj = BaseConstructor("obj1"); //the basic object will be decorated var myObj = simpleDecorator(obj, "aParam"); //the basic object will be decorated with other properties var myObj = complexDecorator(obj, 2, 3); Is this a good way to have Decorator Pattern in javascript? Are there other better ways to do this?

    Read the article

  • Simple check authentication decorator in Python + Pylons

    - by ensnare
    I'd like to write a simple decorator that I can put above functions in my controller to check authentication and re-direct to the login page if the current user is not authenticated. What is the best way to do this? Where should the decorator go? How should I pass cookie info to the decorator? Sample code is greatly appreciated. Thank you!

    Read the article

  • Graph limitations - Should I use Decorator?

    - by Nick Wiggill
    I have a functional AdjacencyListGraph class that adheres to a defined interface GraphStructure. In order to layer limitations on this (eg. acyclic, non-null, unique vertex data etc.), I can see two possible routes, each making use of the GraphStructure interface: Create a single class ("ControlledGraph") that has a set of bitflags specifying various possible limitations. Handle all limitations in this class. Update the class if new limitation requirements become apparent. Use the decorator pattern (DI, essentially) to create a separate class implementation for each individual limitation that a client class may wish to use. The benefit here is that we are adhering to the Single Responsibility Principle. I would lean toward the latter, but by Jove!, I hate the decorator Pattern. It is the epitome of clutter, IMO. Truthfully it all depends on how many decorators might be applied in the worst case -- in mine so far, the count is seven (the number of discrete limitations I've recognised at this stage). The other problem with decorator is that I'm going to have to do interface method wrapping in every... single... decorator class. Bah. Which would you go for, if either? Or, if you can suggest some more elegant solution, that would be welcome. EDIT: It occurs to me that using the proposed ControlledGraph class with the strategy pattern may help here... some sort of template method / functors setup, with individual bits applying separate controls in the various graph-canonical interface methods. Or am I losing the plot?

    Read the article

  • Applying the Decorator Pattern to Forms

    - by devoured elysium
    I am trying to apply the Decorator Design Pattern to the following situation: I have 3 different kind of forms: Green, Yellow, Red. Now, each of those forms can have different set of attributes. They can have a minimize box disabled, a maximized box disabled and they can be always on top. I tried to model this the following way: Form <---------------------------------------FormDecorator /\ /\ |---------|-----------| |----------------------|-----------------| GreenForm YellowForm RedForm MinimizeButtonDisabled MaximizedButtonDisabled AlwaysOnTop Here is my GreenForm code: public class GreenForm : Form { public GreenForm() { this.BackColor = Color.GreenYellow; } public override sealed Color BackColor { get { return base.BackColor; } set { base.BackColor = value; } } } FormDecorator: public abstract class FormDecorator : Form { private Form _decoratorForm; protected FormDecorator(Form decoratorForm) { this._decoratorForm = decoratorForm; } } and finally NoMaximizeDecorator: public class NoMaximizeDecorator : FormDecorator { public NoMaximizeDecorator(Form decoratorForm) : base(decoratorForm) { this.MaximizeBox = false; } } So here is the running code: static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(CreateForm()); } static Form CreateForm() { Form form = new GreenForm(); form = new NoMaximizeDecorator(form); form = new NoMinimizeDecorator(form); return form; } The problem is that I get a form that isn't green and that still allows me to maximize it. It is only taking in consideration the NoMinimizeDecorator form. I do comprehend why this happens but I'm having trouble understanding how to make this work with this Pattern. I know probably there are better ways of achieving what I want. I made this example as an attempt to apply the Decorator Pattern to something. Maybe this wasn't the best pattern I could have used(if one, at all) to this kind of scenario. Is there any other pattern more suitable than the Decorator to accomplish this? Am I doing something wrong when trying to implement the Decorator Pattern? Thanks

    Read the article

  • Decorator Pattern on List<T> for DataGridView

    - by elector
    Hi all, I would like to apply a Decorator on List class and be able to bind it to the WinForms DataGirdView. I would like to know what members of List i need to implement for this new class to be able to bind it to DataGrid. Some of the methods from List I would hide with my decorated class methods and others I would just call _decoratedList.Method(). Is this an option for implementing Decorator on List type? Decorator: public class MyCustomList : List<MyObject> { List<MyObject> _decoratedList; . . . }

    Read the article

  • Merge decorator function as class

    - by SyetemHog
    How to make this merge function as class decorator? def merge(*arg, **kwarg): # get decorator args & kwargs def func(f): def tmp(*args, **kwargs): # get function args & kwargs kwargs.update(kwarg) # merge two dictionaries return f(*args, **kwargs) # return merged data return tmp return func Usage: @other_decorator # return *args and **kwarg @merge(list=['one','two','three']) # need to merge with @other_decorator def test(*a, **k): # get merged args and kwargs print 'args:', a print 'kwargs:', k

    Read the article

  • Decorator Design Pattern Use With Service Objects (wSingleton)

    - by Dustin
    I'm working on a project where I need to add some functionality to a service object and using a decorator to add it in seems like a good fit. However, I've only ever used decorators with simple beans, never on a singleton like a service object. Has anyone ever done this before and what are the pros and cons? In this case I don't think creating a subclass will work so a decorator seems to be a good fit. What are your thoughts on doing this?

    Read the article

  • Pylons FormEncode @validate decorator pass parameters into re-render action

    - by joelbw
    I am attempting to use the validate decorator in Pylons with FormEncode and I have encountered an issue. I am attempting to validate a form on a controller action that requires parameters, and if the validation fails, the parameters aren't passed back in when the form is re-rendered. Here's an example. def question_set(self, id): c.question_set = meta.Session.query(QuestionSet).filter_by(id=id).first() c.question_subjects = meta.Session.query(QuestionSubject).order_by(QuestionSubject.name).all() return render('/derived/admin/question_set.mako') This is the controller action that contains my form. The form will add questions to an existing question set, which is identified by id. My add question controller action looks like this: @validate(schema=QuestionForm(), form='question_set', post_only=True) def add_question(self): stuff... Now, if the validation fails FormEncode attempts to redisplay the question_set form, but it does not pass the id parameter back in, so the question set form will not render. Is it possible to pass the id back in with the @validate decorator, or do I need to use a different method to achieve what I am attempting to do?

    Read the article

  • Issue with child of custom Decorator class in WPF

    - by galacticgrug
    I need a custom border that renders a little differently than a normal border. I made a class that inherited from Decorator as follows class BetterBorder : Decorator { protected override Size ArrangeOverride(Size arrangeSize) { return arrangeSize; } protected override void OnRender(DrawingContext dc) { //these values are calculated elsewhere dc.DrawGeometry(backgroundBrush, borderPen, pathGeometry); } } //Properties and helper methods below this All of this works fine until I try to add a child to the control, the control can be added but is not visible and seems to be moved off BetterBorders visible client area. If I inherit from Border everything works fine, what am I missing?

    Read the article

  • Python lazy property decorator

    - by detly
    Recently I've gone through an existing code base and refactored a lot of instance attributes to be lazy, ie. not be initialised in the constructor but only upon first read. These attributes do not change over the lifetime of the instance, but they're a real bottleneck to calculate that first time and only really accessed for special cases. I find myself typing the following snippet of code over and over again for various attributes across various classes: class testA(object): def __init__(self): self._a = None self._b = None @property def a(self): if self._a is None: # Calculate the attribute now self._a = 7 return self._a @property def b(self): #etc Is there an existing decorator to do this already in Python that I'm simply unaware of? Or, is there a reasonably simple way to define a decorator that does this? I'm working under Python 2.5, but 2.6 answers might still be interesting if they are significantly different.

    Read the article

  • Issue with child of custom Decorator class in WPF (c#)

    - by galacticgrug
    I need a custom border that renders a little differently than a normal border. I made a class that inherited from Decorator as follows class BetterBorder : Decorator { protected override Size ArrangeOverride(Size arrangeSize) { return arrangeSize; } protected override void OnRender(DrawingContext dc) { //these values are calculated elsewhere dc.DrawGeometry(backgroundBrush, borderPen, pathGeometry); } } //Properties and helper methods below this All of this works fine until I try to add a child to the control, the control can be added but is not visible and seems to be moved off BetterBorders visible client area. If I inherit from Border everything works fine, what am I missing?

    Read the article

  • Decorator Pattern - Multiple wrappers or quantity property?

    - by Jiminizer
    I'm making use of the decorator pattern for one of the first times, as part of a Uni project. As far as I can see, the pattern seems to be meant more for adding functionality in a modular manner, however we've been taught it with uses such as a coffee or pizza maker, where the object has modular components that are added - changing properties rather than behaviour. I'm trying to make the most of both uses, however I've come up with a question. In the example in the book we're using (Head First Design Patterns), the pattern is used in a coffee shop creating different coffees. So, for example, milk, froth, sugar, sprinkles are all decorators. How would you implement a system that used the same decorator multiple times (for example, a coffee with two sugars)? Would you rewrap the coffee, or give sugar a quantity property? Or (as i'm starting to suspect) would this never be an issue as the pattern isn't designed to be used this way?

    Read the article

  • Adding a class to the $tag surrounding a <label> in a Zend_Form with the Label decorator

    - by Roderik
    I'm trying to get the following html out of Zend_Form <div class="group wat-cf"> <div class="left"> <label class="label right">Username</label> </div> <div class="right"> <input type="text" class="text_field"> </div> </div> Using the following code: $username->setAttrib("class", "text_field") ->setDecorators(array( 'ViewHelper', 'Description', 'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'div', 'class' => 'right')), array('Label', array('tag' => 'div', 'class' => 'label right')), array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class' => 'group wat-cf')) )); I can get the next fragment <div class="group wat-cf"> <div id="username-label"> <label for="username" class="label right required">Username:</label> </div> <div class="right"> <input type="text" name="username" id="username" value="" class="text_field"> </div> </div> so apart from some extra id's and required classes i don't mind, i need to get a class "left" on div id="username-label" Now adding class to the Label line, gets the class added on the element. I also don't see and option to do this in the Label decorator code itself. So i need a custom Label decorator, or is there some other way i'm missing?

    Read the article

  • access django session from a decorator

    - by ed1t
    I have a decorator that I use for my views @valid_session from django.http import Http404 def valid_session(the_func): """ function to check if the user has a valid session """ def _decorated(*args, **kwargs): if ## check if username is in the request.session: raise Http404('not logged in.') else: return the_func(*args, **kwargs) return _decorated I would like to access my session in my decoartor. When user is logged in, I put the username in my session.

    Read the article

  • Python class decorator and maximum recursion depth exceeded

    - by Michal Lula
    I try define class decorator. I have problem with __init__ method in decorated class. If __init__ method invokes super the RuntimeError maximum recursion depth exceeded is raised. Code example: def decorate(cls): class NewClass(cls): pass return NewClass @decorate class Foo(object): def __init__(self, *args, **kwargs): super(Foo, self).__init__(*args, **kwargs) What I doing wrong? Thanks, Michal

    Read the article

1 2 3 4 5 6 7 8 9  | Next Page >