close
Skip to main content

New answers tagged

Score of 1

Running a Class.method() when that module is imported

The best way to run code while the class is being defined, is to run that code in the class definition. In the comments you mentioned you want to initialise logging and such. Well, just do this in the ...
Score of 2

Running a Class.method() when that module is imported

The class has several ways of running methods when a class is defined - which is usually when the module it is defined in is imported (but also, if it is declared inside a function, for example, when ...
Score of 5
Accepted

Running a Class.method() when that module is imported

You can make a decorator do what you want: def onLoad(cls): cls.onLoad(cls) return cls @onLoad class Class1: var1 = 0 def onLoad(cls): cls.var1 = 1 print(f"{Class1.var1 ...
Score of 2
Accepted

Modifying a class list results in no modification of the list

The list comprehension version works, the second method has these 2 problems: link, link (thanks to @jonrsharpe). The real problem is that you did not recalculate self.NumofPossibilities after ...
Score of 1

Why is the class-level variable not reset for every instance in this implementation of a singleton?

Statements in a class definition that aren't in methods are executed when the class is defined, not each time a method is called. So _instance = None is only performed once when you create the ...

Top 50 recent answers are included