How to get one value from a method in class without recalculating? - python

I am wondering if I can get a value from a method which does not belong to object, and use it in another method under the same class.
Here is a sample code:
class Additon:
def __init__(self,number):
self.number=number
def arithmetic(self,k):
newnumber1=self.number+k
newnumber2 = self.number-k
return [newnumber1,newnumber2]
def add(self):
a=self.arithmetic(1)
return a[0]
def minus(self):
#get new number2
I would like to get newnumber2 in minus method without calling arithmetic again. This is just a sample code for my programming assignment, the result does not matter. I would like to know the way of doing this.

class Additon:
def __init__(self,number):
self.number=number
def arithmetic(self,k):
newnumber1=self.number+k
self.newnumber2 = self.number-k
return [newnumber1,newnumber2]
def add(self):
a=self.arithmetic(1)
return a[0]
def minus(self):
return self.newnumber2

Related

How do I use the function in the class below in the other class without using global

How do I use the function in the class below in the other class without using global?
Code:
class one:
class one_one:
def add(x):
return x+1
class one_two:
ans = one.one_one.add(1)
It certainly is an unusual design, but it will work if you remember to distinguish between classes and instances of classes (objects). In your example you are attempting to call add in the class one_one which is an instance method without first instantiating an object of that class type. The example below shows one way to achieve what you are trying to do by instantiating the objects before calling their methods.
Example:
class one:
class one_one:
def add(self, x):
return x+1
class one_two:
def add(self):
a_one_one = one.one_one()
ans = a_one_one.add(1)
return ans
a_one_two = one.one_two()
print(a_one_two.add())
Output:
2

What would be better way if any to store list of methods that would be easily accessible?

I have a class that has multiple methods and I want to store all of the available methods that would be easily accessible in example would be something like this
class Methods:
def foo(self, a):
return f'hello {a}'
def bar(self, b):
return f'hello {b}'
def methods_dict(self, var, **kwargs):
dic = {
'me' : self.foo(var),
'be': self.bar(var)
}
return dic
But on runtime my methods_dict() method will execute both of the methods inside of it's dictionary.
One one hand I'm planing to store only strings in there and it's really easily accessible, on the other hand i probably would not need to access all of the available methods at once.
Any suggestions ?
I am planning to use those methods as follows
class InheritMethods(Methods):
def __init__(self, method_name):
self.method_name = method_name
def add_to_list(self, input):
arr = []
arr.append(self.method_dicts(input)[self.method_name]
return arr
To clear things up, I am gonna call specific method based on input name, so basically input == method_name
I could do conditional statements like if input == 'foo': do somethings.., but if i end up having a lot of methods, my code is going to be a mess, so i assume(!) that would not be a great idea
I think you can get what you want with the following. Your exact usecase is still not clear. Please respond if I am heading in the wrong direction.
Using self.__getattribute__() you can get a function by name. Of course you would have to catch exceptions etc.
class Methods:
def foo(self, a):
return f'hello {a}'
def bar(self, b):
return f'hello {b}'
class InheritMethods(Methods):
def __init__(self, method_name):
self.method_name = method_name
def add_to_list(self, method_name, input):
method = getattr(self, method_name)
result = method(input)
return [result]
class InheritSingleMethod(Methods):
def __init__(self, method_name):
self.add_to_list = self.getattr(self, method_name)
Output
# Any method version
inherit_methods = InheritMethods('a') # < no use for that argument right?
inherit_methods.add_to_list('foo', 'laurens')
> ['hello laurens']
# Single method version
inherit_single_method = InheritSingleMethod('foo')
inherit_single_method.add_to_list('laurens')
> 'hello laurens'
If all you want to do is access a method of Methods given the name in a str, use getattr:
name = input()
m = Methods()
getattr(m, name)("bob")

invoking a class method inside the class itself

Hi everyone i wanna use a calculated value from a method of the class itself for the rest of the class methods but it must calculate once for all and i need to invoke method inside the class itself i write an example:
class something():
def __init__():
pass
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
# I need to calculate summation here once for all:
# how does the syntax look likes, which one of these are correct:
something.__sum(1, 2)
self.__sum(1, 2)
# If none of these are correct so what the correct form is?
# For example print calculated value here in this method:
def do_something_with_summation(self):
print(self.summation)
Something like this seems to be what you're looking for:
class Something:
def __init__(self):
self.__sum(1, 2)
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
Not saying this is the ideal approach or anything, but you haven't really given us much to go off of.
In general, make sure self is the first argument in all class methods, and you can call that class method at any time using either self.method_name() if you are using it from within another class method or instance.method_name() if you're using it externally (where instance = Something()).
Assuming that you would receive variable1 and variable2 when you instantiate the class one solution could be:
class something():
def __init__(self, variable1, variable2):
self.summation = variable1 + variable2
def do_something_with_summation(self):
print(self.summation)
If instead you're creating variable1 and variable2 inside other methods, then you could make them class variables:
class Something():
def __init__(self):
#Put some initialization code here
def some_other_method(self):
self.variable1 = something
self.variable2 = something
def sum(self):
try:
self.summation = self.variable1 + self.variable2
except:
#Catch your exception here, for example in case some_other_method was not called yet
def do_something_with_summation(self):
print(self.summation)

Use keywords in class to call a specific method

Suppose a Python class has different methods, and depending on what the user specifies, a different method is carried out in the main function calculate().
In the example below the user needs to specify the keyword argument 'methodOne' or 'methodTwo'. If no or an incorrect keyword is specified it should default to 'methodOne'.
class someClass(object):
def __init__(self,method=None):
methodList = ['methodOne','methodTwo']
if method in methodList:
self.chosenMethod = method
else:
self.chosenMethod = self.methodOne
def methodOne(self):
return 1
def methodTwo(self):
return 2
def calculate(self):
return self.chosenMethod()
The above clearly does not work since method is a string and not a function. How can I select self.methedOne() or self.methedOne() based on my keyword argument method? In principle the following works:
def __init__(self,method=None):
if method == 'methodOne':
self.chosenMethod = self.methodOne
elif method == 'methodTwo':
self.chosenMethod = self.methodTwo
else:
self.chosenMethod = self.methodOne
But if I have more than two methods this becomes rather ugly. Is there a way to do this similar to my original code?
You could use getattr() for that purpose:
class someClass(object):
def __init__(self,method=None):
methodList = ['methodOne','methodTwo']
if method in methodList:
self.chosenMethod = method
else:
self.chosenMethod = self.methodOne
def methodOne(self):
return 1
def methodTwo(self):
return 2
def calculate(self):
return getattr(self, self.chosenMethod)()
x = someClass(method='methodOne')
print x.calculate()
>>> 1
You can use getattr to get the actual method on the class object.
class someClass(object):
def __init__(self,method=None):
# store it with the object so we can access it later in calculate method
self.method = method
def methodOne(self):
return 1
def methodTwo(self):
return 2
def calculate(self):
# get the actual method from the string here
# if no such method exists then use methodOne instead
return getattr(self, self.method, self.methodOne)()
> someClass('methodOne').calculate()
# 1
> someClass('methodTwo').calculate()
# 2

Python - Help on genetic algorithm error

I've been trying to create a genetic algorithm in python but i either get:
<bound method Environment.bestsol of <__main__.Environment instance
at 0x10a5d4ab8>>
or it doesn't print. I've tried to rearrange the functions, and call the function directly, but it still does not output anything. I seem to be having trouble with something relating to the function bestsol().
import random
import sys
from operator import attrgetter
input = 1
target = 5.5
class Individual:
def __init__(self, constant):
self.fitness = getfitness()
self.constant = constant
def getconstant():
return self.constant
def getresult():
return self.constant * input
def getfitness():
return 10 - abs(target - self.getresult())
def mutate():
if(random.random() > .05):
self.constant + random.random()
def offspring(partner):
return Individual(((self.getconstant() + partner.getconstant())/2))
class Generation(list):
def __init__(self, gensize, fitsize, startinglist=[]):
self.extend(startinglist)
self.bredoff = []
self.gensize = gensize
self.fitsize = fitsize
self.make()
def make():
self = [Individual(random.randint(-10,10)) for x in xrange((self.gensize-len(self)))]
def getfittest():
return heapq.nlargest(self.fitsize,self,key=attrgetter('fitness'))
def getbredoffspring():
for i in self.getfittest():
bredoff.append(i.offspring(self.getfittest[random.randint(0,len(self.getfittest()))]))
return bredoff
class Environment():
def __init__(self, maxgens):
self.l = []
self.b = []
self.maxgens = maxgens
def create():
l = Generation(100,20)
for i in maxgens:
b = l.getbredoffspring()
l = Generation(100,20,b)
def bestsol():
print("e")
print max(l,key=attrgetter('fitness')).fitness()
def main():
sol = Environment(2)
print sol.bestsol
if __name__ == '__main__':
main()
With me being new to python i can't understand even after searching the internet as best i could. Any help will be appreciated.
bestsol is a class method, so when you call it you should use brackets: sol.bestsol() (otherwise, you're print the method object: <bound method Environment.bestsol ...).
Second, when you define a class-method you should declare self as an argument:
def bestsol(self): # <-- here
print("e")
print max(l,key=attrgetter('fitness')).fitness()
Third, when you declare a class that doesn't extend any other class - you should either declare that it inherits from object (old way):
class Environment(object):
or, no brackets at all (new way)
class Environment:
Forth, when you create a class member, say l (you really should use better names btw), whenever you want to use it you should use the self annotation: self.l. If you'll use l it will create a local variable inside the method - and that's probably not what you intended.
There are other problems with the code but I'll let you struggle with it a bit so you can learn :)

Categories