This question already has answers here:
How to get the caller class name inside a function of another class in python?
(6 answers)
Closed 4 years ago.
I am editing some code that is being called by another system that I do not control. This system initializes my class from a few different places. I need to perform different things depending on where my class is called from.
Is there a way I can find where my object is being initialized?
A.py:
class InitializerA:
def calling_function(self):
Called()
class InitializerB:
def calling_function(self):
Called()
B.py:
class Called:
def __init__(self):
# I want to know here whether it is being called by InitializerA or InitializerB
I was able to find the answer by modifying the method given in this question:
How to get the caller class name inside a function of another class in python?
The inspect library helped me inspect the call stack.
You could pass the class initializing it as an parameter to Called i.e:
class class InitializerA:
def calling_function(self):
Called(self.__name__)
class Called:
def __init__(self, initializer):
self.initializer = initializer
Related
This question already has answers here:
using super without inheritance class in python3
(3 answers)
Closed 2 years ago.
I was looking at a code which a Parent class calls super:
class ParentClass:
def __init__(self):
super(ParentClass, self).__init__()
I don't understand why would someone call super on itself and how does this not get stuck on a recursive loop. Is there something in the background of Python mechanisms that I'm missing?
In python, all classes are implicitly a subclass of object. super will always follow a Method Resolution Order (mro) to determine which function to call. This is explained well in the super docs.
So, for a class like-
class ParentClass:
def __init__(self):
super(ParentClass, self).__init__()
The mro follows - ParentClass -> object
Which means super(ParentClass, self) (or the shorthand, super()) translates to object and object.__init__() is indeed a very valid call.
This question already has answers here:
Does the #staticmethod decorator do anything?
(2 answers)
Closed 3 years ago.
Given that the following code runs without error, why is the staticmethod decorator necessary? What is it actually doing?
class Foo:
def say_hi(name):
print(f'Hello {name}.')
#staticmethod
def say_bye(name):
print(f'See ya later, {name}.')
my_name = 'Bar...t'
Foo.say_hi(my_name)
Foo.say_bye(my_name)
Static methods, much like class methods, are methods that are bound to a class rather than its object.
They do not require a class instance creation. So, they are not dependent on the state of the object.
The difference between a static method and a class method is:
Static method knows nothing about the class and just deals with the parameters.
Class method works with the class since its parameter is always the class itself.
https://www.programiz.com/python-programming/methods/built-in/staticmethod
This question already has answers here:
Define a method outside of class definition?
(5 answers)
Closed 4 years ago.
Is it possible (preserving all the class functionality) to write the class functions in separate files?
Below is an example:
TestClass.py:
class MyClass():
def __init__(self, param1=1, param2=2, param3=3):
self.param1, self.param2, self.param3 =param1, param2, param3,
def ClassFun1(self, param1=2):
return param1**2/self.param2
TestClass2.py:
def ClassFun2(self, param1=3):
return param1*3/self.param2
Next, following this answer, I compile both files (I am too lazy to use import), create a class variable and try to use ClassFun2:
x=MyClass()
x.myMethod=ClassFun2
x.myMethod(2)
As a result, I get an error, since self in ClassFun2 is treated as a parameter, rather than class itself:
AttributeError: 'int' object has no attribute 'param2'
Is it possible to split class definition into several source files? It is possible in C++ and this is actually very convenient when working as a team.
The variable x is an object of the class, not the class itself. You need to do:
x = MyClass
x.myMethod = ClassFun2
Notice that I didn't put () after MyClass. That returns the class itself, it doesn't return an instance of the class.
Then you need to create an instance to execute the method:
y = MyClass()
y.myMethod(2)
This question already has answers here:
What do __init__ and self do in Python? [duplicate]
(18 answers)
Closed 6 years ago.
I am learning oop in python so i am having some problem to understand sefl keyword properly.
Suppose a program :
class ge:
def __init__(self,a,b):
self.p=a
self.l=b
def ff(self):
aaa=self.p+self.l
print(aaa)
hh=ge(1,2)
hh.ff()
I am confuse why its necessary to use any string with self with dot ? what it means ? Like:
self.a=a and we can change self.a to ay string like self.b , self.c what it means ?? why its necessary ?
My second question is :
what is difference between defining class with parameter and without parameter ?
class hello(object):
def __init__(self,a,v):
self.a=a
self.v=v
def p(self):
f=self.a+self.v
print(f)
he=hello(1,2)
he.p()
if i defined
class hello(object) its working but
if i defined class like:
class hello(): its also working
but if i defined like:
class hello: its also working
what is the difference class hello(object): , class hello(), class hello:
First question : Duplicate of this question
Second question : There is no difference between the different notations. When you use the parenthesis it means that your class inherits from the class between parenthesis.
In python 3, by default every class inherits from the class object. So hello(object): , class hello():, class hello: are totally equivalent.
In python 2 however, you must explicit the inheritance.
Here are more details on how to create classes in python.
self is used to reference the instance of the class, is like this in Java
Duplicated:
When do you use 'self' in Python?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between #staticmethod and #classmethod in Python?
I am learning OOP in python and came to know about these two methods
It seems that the difference in terms of syntax is that class methods are implicitly passed the class they belong to as their first parameter
class Circle:
all_circles = [] # class variable
#staticmethod
def total_area():
for c in Circle.all_circles: # hardcode class name
# do somethig
#classmethod
def total_area(cls):
for c in cls.all_circles: # no hardcode class name
# do something
I see class method as more flexible since we don't hardcode the class
Question:
- Is it even a question which one is better? #staticmethod or #classmethod?
- what are the scenarios suitable to use of each one of these methods?
A classmethod gets passed the class 'cls' that it was called upon. For more details see: What is the difference between #staticmethod and #classmethod in Python?