how to get dynamically created method's name - python

I have a method which return its own name. The method looks like this:
import inspect
class example(object):
def getvalue(self):
return inspect.stack()[0][3] #returns current method's name
Now I am creating a method dyamically in that example class like this.
import inspect
class example(object):
def getvalue(self):
return inspect.stack()[0][3] #returns current method's name
if __name__=="__main__":
e = example()
e.method=e.getvalue
print e.method()
This gives the output getvalue.
Now I want my getvalue() method to return dynamic method I created's name i.e method. Is there a way to do it in python? If so what changes do I have to do in my getvalue() method so that it returns dynamically created method's name.
import inspect
class example(object):
def getvalue(self):
return inspect.stack()[0][3] #what to write here...

This is not possible.
In Python the very same object can have multiple "names" and thus it doesn't make sense to talk about "the" name of an object.
Methods are objects and the compiler for functions and methods stores the "name" found when the compiling was done in a __name__ field. If you later move the object around and place it in places reachable using other names the __name__ field it has won't change.

Related

Python Function that creates class instances

Hello i want to create a function which creates instances of a class
def make_instance(name_instance)
name_instance=puppy()
class puppy:
def __init__(self,name):
self.name =name
make_instance(cloud)
# when i pass an argument it says the variable is undefined and i use #isinstance() it return False.
Your puppy class needs to take a name value into its constructor, and you're currently not passing in anything.
Also your function doesn't return the instance at all. It simply re-assigns the instance to the variable name_instance that you pass in (losing your input). The return value of make_instance right now is None
My guess is that you want your implementation to look like the following
def make_instance(name_instance)
return puppy(name_instance)
I do want to point out though that this function isn't useful unless it does more than just create the instance, you're just adding wrapper code around the constructor

When to use self and when not to use self

Which class option is preferable and why?
Option 1
class Person():
def __init__(self):
pass
def sayHello(self, name):
print "{} says hello!".format(name)
def driver(self):
for name in names: # names is generated in the driver function by some means of input
self.sayHello(name)
Option 2
class Person():
def __init__(self):
self.name = None
def sayHello(self):
print "{} says hello!".format(self.name)
def driver(self):
for name in names: # names is generated in the driver function by some means of input
self.name = name
self.sayHello()
You can assume that there are more variables than just name and that multiple functions are using these variables. The main point I am trying to make is that the variable value's are changing inside the for loop
Even though your exemple is syntaxically correct, it doesn't help at all understand your question regarding how to use a instance attribute.
From want I'm guessing, there's two questions :
When to use a class method (def foo(self, bar)) ?
When to use a instance attribute (self.name) ?
Instance attribute should be used when you need to "share" a variable between functions or retrieve it from outside a function. That variable will be "attached" to the object (for exemple, the color of a car, the nickname of a user, ...)
If your function / method need to call this kind of variable, it must use self to get it, so you have to set it as the first argument when defining this function.
If you just need a temporary variable to loop over it and do some stuff, you don't need to use a class method, a simple function will do the trick.

Execute Method within Class Python

I'm trying to call a method within a class MyClass and have its value returned.
class MyClass:
def __init__(self):
print " Class Initialized"
def gather_path(self):
self.tld_object = Tld.objects.get(id=3,FKToClient=User.pk)
return self.tld_object
How do I return the value of self.tld_object by importing my class in Python intrepreter.
I'm importing like:
from MyApp.MyClass import gather_path()
I know, this is quite basic - I'm relatively new to OOP in Python.
how do I then call this method to return the value of return self.tld_object within gather_path() method?
It depends on what you're trying to do, but typically, I think the code importing your class would look like this:
from MyApp import MyClass
my_instance = MyClass()
value = my_instance.gather_path()
The value variable will now contain tld_object's value.
If you don't want to instantiate MyClass in order to call get_path(), you need to make get_path() either a class or static method.
From your example, it's not clear that you need to set self.tld_object, since you're just returning it from gather_path() anyway, unless other methods are relying on that state under the hood. If you are, though, it would be better practice to declare it in __init__, even if you set it to None. Alternatively, if all instances of MyClass are going to use the same value of tld_object, you could make it a class variable, and just declare it outside of any method, like so:
class MyClass:
tld_object = Tld.objects.get(id=3,FKToClient=User.pk)
def gather_path(self):
return self.tld_object
Not sure how much of that is relevant to your needs, it's a bit hard to tell from the given example. If I were writing this (given what you've said so far), I'd do the following:
class MyClass:
def __init__(self):
self.tld_object = Tld.objects.get(id=3,FKToClient=User.pk)
# Maybe raise an exception or something if self.tld_object doesn't get set right
# Example of how to access tld_object from another method
def print_tld_object(self):
print self.tld_object
If you need to reach tld_object from outside the class, you would do the following in the other module:
from MyApp import MyClass
my_instance = MyClass()
tld = my_instance.tld_object

How does one write a method to call after a variable or object, such as "string {0}".format(stringy)?

For different data types, like string, there are methods that you call by adding a dot after, such as:
"string {0}".format(stringy)
or
listx.remove(x)
How is the information being passed to the method? How can I write a function like that?
class YourObject(object):
def do_something(self):
print('doing something')
Then you can use your object:
your_object = YourObject()
your_object.do_something()
This shows how to create an object, and call a method on it (like theexamples you provided in your post).
There are way more in-depth tutorials/blogs about object creation and custom classes. A good place to start is always the standard documentation.
You can create a custom class and then include whatever methods you want. Below is an example:
>>> class MyClass(object): # Define class MyClass
... def __init__(self): # Define MyClass' constructor method
... self.name = "Me" # Make an attribute
... def getName(self): # Define method getName
... return self.name # Return MyClass' attribute name (self.name)
...
>>> test = MyClass() # Initialize (create an instance of) MyClass
>>> print test.getName() # Print the name attribute by calling the getName method
Me
>>>
Basically, you are working with OOP (Object-Oriented Programming). However, since this concept is so large, I can't demonstrate/explain everything you can do with it here (otherwise my post would be enormous). My advice is to research OOP and Python classes. There are many good tutorials you can find. I gave one above; here is another:

python, dynamically implement a class onthefly

Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on_the_fly.
from example
class RemoveNoise():
pass
then methods are added as wanted
RemoveNoise.raw = Raw()
RemoveNoise.bais = Bias()
etc
he can even write a new one
def new():
pass
and also add the new() method
RemoveNoise.new=new
run(RemoveNoise)
run() is a function that evaluates such a class.
I want to save the class_with_the_methods_used and link this class to the object created.
Any hints on how to solve this in python?
Functions can be added to a class at runtime.
class Foo(object):
pass
def bar(self):
print 42
Foo.bar = bar
Foo().bar()
There is no solving needed, you just do it. Here is your code, with the small changes needed:
class RemoveNoise():
pass
RemoveNoise.raw = Raw
RemoveNoise.bias = Bias
def new(self):
pass
RemoveNoise.new=new
instance = RemoveNoise()
It's that simple. Python is wonderful.
Why on earth you would need this is beyond me, though.
Well, here's some code that does what I think you're asking for -- although I'm not really sure what you meant by "save" when you wrote "I want to save the class_with_the_methods_used". Also note that using an exec statement on user input can be extremely dangerous if it comes from an untrusted source.
import copy
# an empty "template" class
class Generic():
pass
# predefined functions that create common methods
def Raw():
def raw(self):
print 'in Raw method of instance', id(self)
return raw
def Bias():
def bias(self):
print 'in Bias method of instance', id(self)
return bias
def user_new_function(definition):
tempdict = {}
exec definition in tempdict
return tempdict['new']
# create a new class
RemoveNoise = copy.deepcopy(Generic)
RemoveNoise.__name__ = 'RemoveNoise' # change the class name of the copy
# add a couple of predefined methods
RemoveNoise.raw = Raw()
RemoveNoise.bias = Bias()
# add user defined 'new' method
user_new_def = """\
def new(self):
print 'in user defined method "new" of instance', id(self)
"""
RemoveNoise.new = user_new_function(user_new_def)
# create and use an instance of dynamically defined class
instance = RemoveNoise()
print 'RemoveNoise instance "{}" created'.format(id(instance))
# RemoveNoise instance "11974736" created
instance.raw()
# in Raw method of instance 11974736
instance.bias()
# in Bias method of instance 11974736
instance.new()
# in user defined method "new" of instance 11974736

Categories

Resources