get object on which a method was called in Python - python

Is there a way in Python to get a reference to an object on which a method was called?
And in case it is, is it possible even in a nested way?
my_class.py:
from modules import math_ops
class A():
def __init__(self):
self.math_ops = math_ops.B()
self.number = 1
modules/math_ops.py:
class B():
def add_1():
where_to_add = # Get instance of A() object
where_to_add.number += 1
To execute this:
>>> a = A()
>>> a.math_ops.add_1()
And get this:
>>> a.number
2
I'm asking because I am interested in writing a static method which works with the object on which it was called, but would like to avoid using the object as an argument as it would be much nicer to call a method like my_object.prop.static_method() instead of my_object.prop.static_method(my_object).

If you never plan on reassigning math_ops outside A, this is fairly simple to do.
from modules import math_ops
class A():
def __init__():
self.math_ops = math_ops.B(self)
self.number = 1
modules/math_ops.py:
class B():
def __init__(self, creator):
self.creator = creator
def add_1():
creator.number += 1
I will mention it again in case you skimmed the first line, the following will generate unexpected results since B is tracking the creator of the object rather than the caller.
a1 = A()
a2 = A()
a1.math_ops = a2.math_ops
a1.math_ops.add_1() # a2 is updated
If that looks like something you might wanna do, the answer is a tad more complicated. Here's my attempt:
from modules import math_ops
class A():
def __init__(self):
self._math_ops = math_ops.B(self)
self.number = 1
#property
def math_ops(self):
self._math_ops.set_caller(self)
return self._math_ops
#math_ops.setter
def math_ops(self, new_math_ops):
self._math_ops = new_math_ops
modules/math_ops.py:
class B():
def __init__(self, caller):
self.caller = caller
def set_caller(self, caller):
self.caller = caller
def add_1(self):
self.caller.number += 1

class A():
number = 1
class B():
def add_1():
where_to_add = A
where_to_add.number += 1
B.add_1()
print(A.number)
B.add_1()
print(A.number)
B.add_1()
print(A.number)

Related

Can the inherited class see the change of the value on the parent class?

I have two classes. class A has a public variable X, which is used by both classes,
class A changes the value of X every 3 seconds, while class B prints the new value of X. But the class B sees the initial value 10 only. I need class B to see the change of the variable X in Class A.
import threading
import time
class A():
X = 10
def __init__(self):
self.first()
def first(self):
while True:
self.X = self.X + 3
print("A",self.X)
time.sleep(3)
class B(A):
def __init__(self):
t = threading.Thread(target= self.second, args=())
t.setDaemon(True)
t.start()
def second(self):
while True:
print(self.X)
time.sleep(3)
example1 = B()
example2 = A()
This is not setting the class variable X.
self.X = self.X + 3
On the first iteration self.X is reading the class variable since there is no instance variable X.
However it assigns the instance variable and from that point on, self.X within A is an instance variable and any changes made are not reflected in A.X.
You can fix this by making the first argument of the method (self) refer to the class and not the instance with the #classmethod decorator.
#classmethod
def first(cls):
while True:
cls.X = cls.X + 3
print("A",cls.X)
time.sleep(3)
Full code:
import threading
import time
class A():
X = 10
def __init__(self):
self.first()
#classmethod
def first(cls):
while True:
cls.X = cls.X + 3
print("A",cls.X)
time.sleep(3)
class B(A):
def __init__(self):
t = threading.Thread(target= self.second, args=())
t.setDaemon(True)
t.start()
def second(self):
while True:
print(self.X)
time.sleep(3)
example1 = B()
example2 = A()
You can access its parent's X, A's x, by either using: A.x or super().x
It doesn't work the way you think it should work. The objects A() and B() are not the same as classes A and B. The objects are separated instances. When you change x using object A(), object B() doesn't know anything about the change that happened. And it couldn't.
If you need it to work the way you want, you should add A() into b's initializer. And then call the variable of A() object.
class B:
def __init__(self, A_instance):
self.a = A_instance
def working(self):
x = self.a.x

Can we pass the class object inside its own method?

I have a class A object method which uses another class B object's method, which the argument is class A object.
class A():
def calculate(self):
B = B.calculator(A)
class B():
def calculator(self, A):
...do something with A.attributes
It is possible to just pass attributes into the object, but I would see this possibility as the last priority. I am definitely a bit oversimplify my case, but I am wondering if there is a way to pass the entire class
Edit:
Sorry for the confusion. At the end I am trying to call class A object and A.calculate(), which will call class B obj and calculator function.
class A():
def __init__(self, value):
self.value = value
def calculate(self):
Bobj = B()
Bobj.calculator(A)
class B():
def calculator(self, A):
...do something with A.value
def main():
Aobj = A(value)
Aobj.calculate()
Your scenario does not currently indicate that you want to use any information from B when calculating A. There are a few ways of getting the functionality that you want.
Scenario: B stores no information and performs calculation. B should be a function
def B(value):
```do something with value```
return
class A():
def __init__(self, value):
self.value = value
def calculate(self):
return B(self.value)
def main():
Aobj = A(value)
Aobj.calculate()
Scenario: B stores some other information, but internal B information is not needed for the calculation. B should have a static method
class B():
#staticmethod
def calculate(value):
```do something with value```
return
class A():
def __init__(self, value):
self.value = value
def calculate(self):
return B.calculate(self.value)
def main():
Aobj = A(value)
Aobj.calculate()

Python class multiple initialization definition based on where it is initialized

What i want to do is make an object do different initializations based on where it is instanciated.
For example
class Test:
def __init__(self):
self.a = 1
def __init2__(self):
self.a = 2
So that the normal init is run when the class Test is called on it's own
t = Test()
print(t.a)
>>> 1
And when it is on a list it runs inside a List it runs the second init
t = [Test()]
print(t[0].a)
>>> 2
Is this possible in python?
You can try a different approach, and just use a #classmethod as a factory method that creates an instance for the specific case:
class Test:
def __init__(self, a=1):
self.a = a
#classmethod
def in_list(cls):
return cls(2)
so, in the list you can call:
t = [Test.in_list()]
print(t[0].a)
>>> 2

Python Class Objects Attribute Referencing

I have two classes. a and b.
In one of class a's methods, I created an object of class b. One of class b attributes takes a function. So say I gave it a random function but does this function of class b have access to class a's attribute? even though I didn't pass it in directly as a parameter?
class b:
def __init__(self):
self.attribute_function = None
class a:
def __init__(self):
self.temp = 10
self.counter = 0
def temp(self):
obj = b()
obj.attribute_function = lambda self: self.counter < self.temp
return obj.attribute_function()
if __name__ == "__main__":
#pass
obj = a()
print obj.temp()
In the above example, I tried to provide a really basic example, but if you run it, it doesn't work...
Revised Code, class a should look like this:
class a:
def __init__(self):
self.temp = 10
self.counter = 0
def temp(self):
obj = b()
obj.attribute_function = lambda args: self.counter < self.temp
return obj.attribute_function(1) # i added this 1 to fill in arg
This works:
class b:
def __init__(self):
self.attribute_function = None
class a:
def __init__(self):
self._temp = 10
self.counter = 0
def temp(self):
obj = b()
obj.attribute_function = lambda self=self: self.counter < self._temp
return obj.attribute_function()
if __name__ == "__main__":
obj = a()
print obj.temp()
On problem you had is self.temp = 10 which shadowed your method temp().
Another problem: lambda self: self.counter < self._temp. Your lambda function was expecting an argument. But omitting self is not a good idea lambda : self.counter < self._temp, because if you call obj.attribute_function() somewhere where self is not available or has changed - it will not find self or use another self. self=self fixes that.
But generally such magic is an anti-pattern. Tell us what are your trying to achieve, and there should be a better way to do what you want. Otherwise this kind of code will ensure many headaches.
I think this is a better solution (called strategy pattern):
class B:
def __init__(self, a):
self.a = a
def temp(self):
return self.a.temp()
class A:
def __init__(self):
self._temp = 10
self.counter = 0
def temp(self):
return self.counter < self._temp
if __name__ == "__main__":
obj = B(A())
print obj.temp()
Your example does not work because you have a name collision at temp
You have assigned temp to be both a method:
def temp(self):
and an attribute:
self.temp = 10

Problem with Python nested objects being stored in a dictionary

I'm having some trouble with changing the value of a class at runtime and then instantiating it into an object, then storing that object inside of another class and putting that into python dictionary.
Here is a small code snippet I wrote to illustrate the problem:
import unittest
class cls1(object):
def __init__(self, obj):
self.obj = obj
class cls2(object):
def __init__(self):
self.var = 1
class Testdict(unittest.TestCase):
def __init__(self):
self.objs = dict()
def runTest(self):
obj2 = cls2()
obj1 = cls1(cls2())
self.objs["test1"] = obj1
self.assertEqual(self.objs["test1"].obj.var, 1)
cls2.var = 2
self.assertEqual(cls2.var, 2)
obj1 = cls1(cls2())
self.objs["test2"] = obj1
self.assertEqual(self.objs["test1"].obj.var, 1)
self.assertEqual(self.objs["test2"].obj.var, 2)
if __name__ == "__main__":
d = Testdict()
d.runTest()
Why would cls2 not instantiate with having it's var equal to 2?
I hope this question makes some sense.
What you're showing can't work. Ever.
class Cls2(object):
def __init__(self):
self.var = 1
That's an instance variable. It's not a class variable. You can't access that .var with Cls2.var That variable only exists within each unique instance of the class.
Cls2.var = 2
Does not change the self.var instance variable. That creates a new class variable in the Cls2 class.
You'd need to do something like this.
class Cls2(object):
default= 1
def __init__(self):
self.var = Cls2.default
Now you can do
Cls2.default= 2
And the rest of whatever it is you're doing should work.
Your test would work if cls2 didn't overwrite cls.var when it is instantiated.
Try this:
class cls2(object):
def __init__(self):
try:
self.var
except:
self.var = 1
The try statement just checks to see if you've already set var.

Categories