class-method

How to make a class property?

How to make a class property? Question: In python I can add a method to a class with the @classmethod decorator. Is there a similar decorator to add a property to a class? I can better show what I’m talking about. class Example(object): the_I = 10 def __init__( self ): self.an_i = 20 @property def …

Total answers: 9

Attaching a decorator to all functions within a class

Attaching a decorator to all functions within a class Question: I don’t really need to do this, but was just wondering, is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function. I suppose it then becomes a kind of aspect, rather than …

Total answers: 11

__getattr__ for static/class variables

__getattr__ for static/class variables Question: I have a class like: class MyClass: Foo = 1 Bar = 2 Whenever MyClass.Foo or MyClass.Bar is invoked, I need a custom method to be invoked before the value is returned. Is it possible in Python? I know it is possible if I create an instance of the class …

Total answers: 5

Using super with a class method

Using super with a class method Question: I’m trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example Traceback (most recent call last): File “<stdin>”, line 1, in <module> File “test.py”, line 9, in do_something do_something = …

Total answers: 5

Calling a base class's classmethod in Python

Calling a base class's classmethod in Python Question: Consider the following code: class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print ‘In derived!’ # Base.do(cls, a) — can’t pass `cls` Base.do(a) if __name__ == ‘__main__’: d = Derived() d.do(‘hello’) > $ python play.py > In derived! > <class …

Total answers: 4

Is it bad form to call a classmethod as a method from an instance?

Is it bad form to call a classmethod as a method from an instance? Question: Ex. If I have something like this: class C(object): @classmethod def f(cls, x): return x + x This will work: c = C() c.f(2) 4 But is that bad form? Should I only call C.f() or c.__class__.f() Obviously, this would …

Total answers: 6

Can you use a string to instantiate a class?

Can you use a string to instantiate a class? Question: I’m using a Builder pattern in Python to separate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named ID… (e.g. ID12345). These all inherit from the base Builder class. In my script, I need to instantiate an instance …

Total answers: 6