Is there a generic way for a function to reference itself?

There is no generic way for a function to refer to itself. Consider using a decorator instead. If all you want as you indicated was to print information about the function that can be done easily with a decorator: from functools import wraps def showinfo(f): @wraps(f) def wrapper(*args, **kwds): print(f.__name__, f.__hash__) return f(*args, **kwds) return … Read more

TypeError: generatecode() takes 0 positional arguments but 1 was given

When you call a method on a class (such as generatecode() in this case), Python automatically passes self as the first argument to the function. So when you call self.my_func(), it’s more like calling MyClass.my_func(self). So when Python tells you “generatecode() takes 0 positional arguments but 1 was given”, it’s telling you that your method … Read more

How can I decorate an instance method with a decorator class?

tl;dr You can fix this problem by making the Timed class a descriptor and returning a partially applied function from __get__ which applies the Test object as one of the arguments, like this class Timed(object): def __init__(self, f): self.func = f def __call__(self, *args, **kwargs): print(self) start = dt.datetime.now() ret = self.func(*args, **kwargs) time = … Read more

Why isn’t self always needed in ruby / rails / activerecord?

This is because attributes/associations are actually methods(getters/setters) and not local variables. When you state “parent = value” Ruby assumes you want to assign the value to the local variable parent. Somewhere up the stack there’s a setter method “def parent=” and to call that you must use “self.parent = ” to tell ruby that you … Read more

What is the difference between class and instance variables?

When you write a class block, you create class attributes (or class variables). All the names you assign in the class block, including methods you define with def become class attributes. After a class instance is created, anything with a reference to the instance can create instance attributes on it. Inside methods, the “current” instance … Read more

“TypeError: method() takes 1 positional argument but 2 were given” but I only passed one

In Python, this: my_object.method(“foo”) … is syntactic sugar, which the interpreter translates behind the scenes into: MyClass.method(my_object, “foo”) … which, as you can see, does indeed have two arguments – it’s just that the first one is implicit, from the point of view of the caller. This is because most methods do some work with … Read more