Find which function is using a given class in python - python

I have class
class A:
def __init__(self):
print(i was used by :)
# if i call this class from the function below,
def my_func():
a = A()
# I need class A to print that "i was used in: my_func() "
Is there any solution for this ?

If you know the function name:
You could try something like:
class A:
def __init__(self, func):
print('i was used by:', func.__name__)
def my_func(func):
a = A(func)
my_func(my_func)
Output:
i was used by: my_func
This you would specify the function instance, which is the most optimal way here, then just use the __name__ to get the name of the function.
If you don't know the function name:
You could try the inspect module:
import inspect
class A:
def __init__(self):
print('i was used by:', inspect.currentframe().f_back.f_code.co_name)
def my_func():
a = A()
my_func()
Or try this:
import inspect
class A:
def __init__(self):
cur = inspect.currentframe()
a = inspect.getouterframes(cur, 2)[1][3]
print('i was used by:', a)
def my_func():
a = A()
my_func()
Both output:
i was used by: my_func

Related

variable inside of function how to use that variable outside of function in python

How to use variable outside of function which is define inside of function?
And Function should declare in class.
class A:
def aFunction(self):
aVariable = "Hello"
Now here I want to use that aVariable
If you want to use this variable within the class A, how about using an instance variable?
class A:
def aFunction(self):
self.aVariable = "Hello"
Now you can use self.aVariable in another function of the same class
There are definitely more options that maybe others will provide, but these are the options I have come up with.
Use return
class A:
def aFunction(self):
aVariable = "Hello"
return aVariable
obj = A()
var = obj.aFunction()
print(var)
use global
class A:
def aFunction(self):
global aVariable
aVariable = "Hello"
obj = A()
obj.aFunction()
print(aVariable)
You can use self to your advantage
class A:
def __init__(self):
self.aVariable = None
def aFunction(self):
self.aVariable = "Hello"
obj = A()
obj.aFunction()
print(obj.aVariable)
To use a variable from a class outside of the function or entire class:
class A:
def aFunction(self):
self.aVariable = 1
def anotherFunction(self):
self.aVariable += 1
a = A() # create instance of the class
a.aFunction() # run the method aFunction to create the variable
print(a.aVariable) # print the variable
a.anotherFunction() # change the variable with anotherFunction
print(a.aVariable) # print the new value
There are several methods you can try.
class A:
def aFunction(self):
self.aVariable = "Hello"
# you can access self.aVariable in the class
class A:
def aFunction(self):
aVariable = "Hello"
return aVariable
# use self.aFunction() whenever you need this variable
The return keyword will return the value provided. Here, you have provided self.aVariable. Then, you can assign the value to a variable outside the class and print the variable.
class A:
def aFunction(self):
self.aVariable = "Hello"
return self.aVariable
a = A() #==== Instantiate the class
f=a.aFunction() #==== Call the function.
print(f)
This will print: Hello

Using user input to call a function from a class

I am trying to call a function from a class based on user input. I've tried other examples based on this but keep on getting various errors depending on which direction I try it.
The test code that I am using is
def one():
print('one hahah')
def two():
print('two hahah')
def the_count():
print('I am the count who likes to count')
dispatcher = {
'one': one, 'two': two, 'three': the_count
}
action = input('Option: - ')
jo.dispatcher[action]()
There we have what I want, but once I added the self argument things stopped working properly.
Here is my actual code...
import math
class femblem(object):
def j(self):
print('hi')
`data goes here`
...
def __init__(self,lv,name):
self.lv = lv
self.name = name
dispatcher = {
'j': j(self)
}
action = input('Character: - ')
unit1 = femblem(5,"joshua")
unit1.dispatcher[action]()
returns NameError: name 'self' is not defined
if I take out self it gives me an error saying that it needs that for an argument (which it does).
Not very experienced in python, any ideas why this isnt working?
Thanks
Essentially, your class will act like a dict here, and your instance is the dispatcher so just use getattr and the self magic will work:
>>> class Foo:
... def bar(self):
... return 42
... def baz(self):
... return 88
...
>>> foo = Foo()
>>> getattr(foo, 'bar')()
42
>>> getattr(foo, 'baz')()
88
>>>
There are several ways you could approach this problem, one of which would be to make dispatcher an instance method of the class:
class Foo(object):
def __init__(self,lv,name):
self.lv = lv
self.name = name
def one(self):
print('this is one!')
def dispatcher(self, action):
d = {'one':self.one}
return d[action]
Then you get something like:
>>> f = Foo(5, 'Joshua')
>>> action = input()
>>> f.dispatcher(action)()
'this is one!'
I can only guess what you are trying to do, but this snippet dispatches to the respective functions defined in your dispatcher for the user inputs one, two and three:
class femblem:
def __init__(self, lv, name):
self.lv = lv
self.name = name
def one(self):
print('one hahah')
def two(self):
print('two hahah')
def the_count(self):
print('I am the count who likes to count')
#property
def dispatcher(self):
return {
'one': self.one,
'two': self.two,
'three': self.the_count
}
action = input('Character: - ')
unit1 = femblem(5, "joshua")
unit1.dispatcher[action]()
An alternative answer with getattr inside the class:
class Foo:
def __init__(self):
pass
def bar(self):
print('this is foo')
def dispatcher(self):
att = input('put some input: ')
getattr(self, att)()
ob = Foo()
ob.dispatcher()

get object on which a method was called in 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)

Calling function from string name within object

I have the following two classes:
class A(object):
def caller(self,name):
# want to invoke call() here when name="call"
class B(A):
def call(self):
print("hello")
Given the following:
x= B()
x.caller("call") # I want to have caller() invoke call() on the name.
I don't want to check the value of name I want it to automatically invoke the the given string as a function on self.
Use __getattribute__
class A(object):
def caller(self,name):
self.__getattribute__(name)()
class B(A):
def call(self):
print("hello")
x= B()
x.caller("call")
Output
hello
can also use eval
class A(object):
def caller(self,name):
eval('self.%s()' % name)
class B(A):
def call(self):
print("hello")
x= B()
x.caller("call")
output
hello
[Finished in 0.6s]

python variable method name

How can you execute a method by giving its name, from another method that is in the same class with the called method? Like this:
class Class1:
def __init__(self):
pass
def func1(self, arg1):
# some code
def func2(self):
function = getattr(sys.modules[__name__], "func1") # apparently this does not work
Any suggestion?
how about getattr(self, "func1")? Also, avoid using the name function
For example:
>>> class C:
... def f1(self, arg1): print arg1
... def f2(self): return getattr(self, "f1")
...
>>> x=C()
>>> x.f2()(1)
1
You should get the attribute from the class, not the module.
def func2(self):
method = getattr(self, "func1")
method("arg")
But you should also check that it's callable.
if callable(method):
method("arg")
This will avoid calling something that you didn't expect to get. You may want to raise your own exception here if it is not callable.

Categories