I have a class with two functions:
class MyClass():
def function1(self):
a = 123
b = 723
c = 813
return a + b + c
def function2(self):
a = 123
b = 723
c = 813
return a - b - c
My question is... Is it possible for function2 to have the similar a, b, and c variables from function1 without declaring those variables again?
Given your current code, the variables "a", "b" and "c" will be local to the functions. If you want to input them once and not again, you should give them when you build your object, so provide them to the constructor/builder as inputs.
class MyClass():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def function1(self):
return self.a + self.b + self.c
def function2(self):
return self.a - self.b - self.c
obj = MyClass(5, 3, 2)
print('F1: ', obj.function1())
print('F2: ', obj.function2())
Output:
F1: 10
F2: 0
Related
This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 4 months ago.
In the example below, classes AA and BB are instantiated with params a and b and feature the foo method. The only difference between classes AA and BB is that in the AA foo method, the intermediate variable z is prefixed with the class instance reference self while in class BB it is not. What is the correct methodology here? When should self be used within class methods and when should it not be used? I've always been confused by this!
class AA:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
self.z = self.a + self.b
return self.z * self.a
class BB:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
z = self.a + self.b
return z * self.a
Neither one is "correct" per se. It depends what you want to do: If you want to keep the value around, then you could assign it to the instance. If not, then don't.
Although, if you do assign it as a public instance attribute, you'll probably want to set an initial value in __init__(), like None.
the use of the self will appear when you initiate an object from the class, so in order that the object will have an access to the variable you need to use the self
class AA:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
self.z = self.a + self.b
return self.z * self.a
class BB:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
z = self.a + self.b
return z * self.a
A = AA(1, 2)
A.foo()
print(A.z) # will print the value
B = BB(1, 2)
B.foo()
print(B.z) # will not print the value, "z" attribute is not defined
I've written a code with 3 different classes - those classes initializes functions and connected between each other (class B calls function a_calc() from A class; class C calls function b_calc() from B class). I want to create Calculator() function that instantiates all of those classes (A, B, C), uses class functions in one line of code, and returns the result of execution (to be able to execute the program creating only one object Main). Here the snippet of code (simplified):
class A(object):
def __init__(self):
self.a = 10
def a_calc(self):
a = self.a + 1
return a
class B(object):
def __init__(self, A):
self.A = A
def b_calc(self):
b = self.A.a_calc() + 2
return b
class C(object):
def __init__(self, B):
self.B = B
def c_calc(self):
c = self.B().b_calc + 3
return c
class Calculator(A, B, C):
def __init__(self):
result = A.a_calc() + B.b_calc() + C.c_calc()
print(result)
calc = Calculator()
Yet, I'm getting an error:
Traceback (most recent call last):
File "/home/taras/PycharmProjects/ResSysPymage/test#2.py", line 31, in <module>
calc = Calculator()
File "/home/taras/PycharmProjects/ResSysPymage/test#2.py", line 27, in __init__
result = A.a_calc() + B.b_calc() + C.c_calc()
TypeError: a_calc() missing 1 required positional argument: 'self'
How can I make my idea come true? I'd be grateful for ideas:)
You seem to be confusing classes, instances of classes and composition vs. multiple inheritance.
Perhaps you're looking for something like this:
class A:
def __init__(self):
self.a = 10
def a_calc(self):
a = self.a + 1
return a
class B:
def __init__(self, a: A):
self.a = a
def b_calc(self):
b = self.a.a_calc() + 2
return b
class C:
def __init__(self, b: B):
self.b = b
def c_calc(self):
c = self.b.b_calc() + 3
return c
def calculator():
a = A()
b = B(a)
c = C(b)
return a.a_calc() + b.b_calc() + c.c_calc()
print(calculator())
I have a dictionary of values and initialize an object.
The dictionary values contains all the modules of the object, so how can I achieve something like this?
test_action = {
'1': 'addition',
'2': 'subtraction'
}
class test:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
def addition(self):
return self.a + self.b + self.c
def subtraction(self):
return self.a - self.b - self.c
def main():
xxx = test(10,5,1)
for key,action in test_action.items():
print(xxx.action())
You should refer to the functions as objects rather than strings, so that:
class test:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
def addition(self):
return self.a + self.b + self.c
def subtraction(self):
return self.a - self.b - self.c
test_action = {
'1': test.addition,
'2': test.subtraction
}
xxx = test(10,5,1)
for key, action in test_action.items():
print(key, action(xxx))
would output:
1 16
2 4
def main():
xxx = test(10,5,1)
for key,action in test_action.items():
if hasattr(xxx, action):
print "perforning: {}".format(action)
print xxx.__getattribute__(action)()
#op
perforning: addition
16
perforning: subtraction
4
If I have a class as such:
class Sample:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
I can create an object by:
temp = Sample(a=100,b=100,c=100)
But what if I have:
my_str = "a=100,b=100,c=100"
How can I temp = Sample(my_str) properly?
You can parse and eval the string like:
Code:
#classmethod
def from_str(cls, a_str):
return cls(**eval("dict({})".format(a_str)))
Test Code:
class Sample:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
#classmethod
def from_str(cls, a_str):
return cls(**eval("dict({})".format(a_str)))
x = Sample.from_str("a=100,b=100,c=100")
print(x.a)
Results:
100
use eval
temp = eval("Sample("+my_str+")")
Although it is definitely an option, using eval can be dangerous. Here is an option which is #StephenRauch's code just without using eval.
>>> class Sample:
... def __init__(self, a, b, c):
... self.a = a
... self.b = b
... self.c = c
...
... #classmethod
... def from_str(cls, a_str):
... result = {}
... for kv in a_str.split(','):
... k, v = kv.split('=')
... result[k] = int(v)
... return cls(**result)
...
>>> x = Sample.from_str('a=100,b=100,c=100')
>>> x.a
100
>>> type(x.a)
<class 'int'>
You can use the below code.
class Sample:
def __init__(self, a, b, c):
self.a = int(a)
self.b = int(b)
self.c = int(c)
mystr = "a=100,b=100,c=100"
temp = Sample(mystr.split(",")[0].split("=")[1],mystr.split(",")[1].split("=")[1],mystr.split(",")[2].split("=")[1])
print(temp.a)
print(temp.b)
print(temp.c)
See it in action here
This works for me:
my_str = "a=100,b=100,c=100"
temp = Sample(int(my_str.split(',')[0].split('=')[1]),
int(my_str.split(',')[1].split('=')[1]),
int(my_str.split(',')[2].split('=')[1]))
print(temp.a)
# prints 100
print(temp.b)
# prints 100
print(temp.c)
# prints 100
I am starting to work with classes in Python, and am learning how to create functions within classes. Does anyone have any tips on this sample class & function that I am testing out?
class test:
def __init__(self):
self.a = None
self.b = None
self.c = None
def prod(self):
return self.a * self.b
trial = test
trial.a = 4
trial.b = 5
print trial.prod
Ideally the result would be to see the number 20.
You need to:
Create an instance of test.
Invoke the prod method of that instance.
Both of these can be accomplished by adding () after their names:
trial = test()
trial.a = 4
trial.b = 5
print trial.prod()
Below is a demonstration:
>>> class test:
... def __init__(self):
... self.a = None
... self.b = None
... self.c = None
... def prod(self):
... return self.a * self.b
...
>>> trial = test()
>>> trial.a = 4
>>> trial.b = 5
>>> print trial.prod()
20
>>>
Without the parenthesis, this line:
trial = test
is simply assigning the variable trial to class test itself, not an instance of it. Moreover, this line:
print trial.prod
is just printing the string representation of test.prod, not the value returned by invoking it.
Here is a reference on Python classes and OOP.
Ideally you could also pass in the values to a, b, c as parameters to your object's constructor:
class test:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def prod(self):
return self.a * self.b
Then, constructing and calling the function would look like this:
trial = test(4, 5, None)
print trial.prod()