Accessing Methods of a class using function parameter in python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a class like this in python:
class xyz:
def abc():
#Do Something
def add(x,y):
#Add x and y
def sub(x,y):
#Subtract y from x
def mul(x,y):
#multiply x ynd y
Note: Here "add", "sub" and "mul" are nested methods.
Is it allowed to make a class like this?
If it is allowed, then i want to access the methods "add", "sub" and "mul" by function parameters. for e.g.:
from xyz import xyz
def jkl(input):
abc.(input) # By doing this it will raise syntax error. This is just for refernece.
so, when i call jkl(add(2,3)) it should add the numbers. Similarly when i call jkl(sub(4,3)) it should subtract the numbers.
Can it be done?

It's hard to understand exactly what your goal is here.
EDIT: I'll leave this answer here since it has received an upvote, but OP clarified that they're actually asking how to overload operators.
You can do this:
class abc():
//Do Something
#staticmethod
def add(x,y):
# Add x and y
#staticmethod
def sub(x,y):
# Subtract y from x
#staticmethod
def mul(x,y):
# multiply x ynd y
abc.add(1,1)
If you want to use your class in another module, you can put that class definition in file xyz.py, and then in another file (in the same directory):
from xyz import abc
abc.add(1,1)
However, this is a very odd thing to do in the Python world. I'd advise organizing things differently, unless you have a really good reason to do things this way. A better way would be to skip the class definition altogether, and do this in abc.py:
def add(x,y):
# Add x and y
def sub(x,y):
# Subtract y from x
def mul(x,y):
# multiply x ynd y
Then import from that module:
import abc
abc.add(1,1)
etc...
Alternatively, you can do this:
from abc import add, sub, mul
add(1,1)
etc...

Related

"def" bringing the wrong answer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I made a class with some functions:
But when I instantiate the values the answer is bringing me 'alimentos', but that's wrong it should be 'portugues' .
I have two dictionaries and this class:
professores_x = {
'alimentos': [{"prof_id":"xx_alimento_1", "prof_disc":"alimentos"},
{"prof_id":"xx_alimento_2", "prof_disc":"alimentos"}],
'português': [{"prof_id":"xx_port_1", "prof_disc":"português"},
{"prof_id":"xx_port_2", "prof_disc":"português"}]}
courses_x = {'alimentos': [{"course_name":"padeiro_confeiteiro"},
{"course_name":"padeiro_confeiteiro"}]}
# trying refactoring
class Disciplinas_cursos_1:
"Define the disciplinas and professors"
def __init__(self,cursos_,professores_):
self.cursos_ = cursos_
self.professores_ = professores_
for self.p in self.cursos_.keys():
if self.p == 'alimentos': self.alimentos()
elif self.p == 'português': self.portugues()
def alimentos(self):
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_al = self.p
discipl_alimentos = [self.p,[x['prof_id'] for x in profiel_prof_disc
if x['prof_disc'] == prof_disc_al]]
return discipl_alimentos
def portugues(self):
print("Now its portuguese turn")
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_port = self.p
print(f"see I'm printing {prof_disc_port}. It's that the same of portuguese? If' not it's wrong")
discipl_port =[self.p,[x['prof_id'] for x in profiel_prof_disc if x['prof_disc'] ==prof_disc_port]]
print(f"see I'm printing {prof_disc_port} and {discipl_port}")
return discipl_port
# ok!! Now I do the instance:
disc_a = Disciplinas_cursos_1(courses_x, professores_x)
disc_a.alimentos()
Output
['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Nice, that is what I want but when I try the second function it's bring me 'alimentos'
but I need 'portugues' and not 'alimentos'.
disc_a.portugues()
Output
Now its portuguese turn
see I'm printing alimentos. It's that the same of portuguese? If' not it's wrong
see I'm printing alimentos and ['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Your issue is with self.p. In __init__, you're setting that value with your loop, and when you call self.alimentos() or self.portugues() in the body of the loop it will make sense since the self.p value will correspond to the method being called.
But if you call disc_a.portugues() from outside of __init__, you're going to get the last value self.p had after the loop, which may not match up at all with the method you're calling. That's why you're getting invalid output, it's using an inappropriate self.p key.
I don't have a firm understanding of what you're intending to do in your methods, so I don't really have a recommended fix. But in general, I'd suggest you think more carefully about which values you're passing to which parts of your code as attributes and as arguments. self.p should probably not exist as an attribute. Maybe it should be an argument to the methods? Maybe you need different attributes to sort your data into separate containers, rather than repeatedly looping over it all. You may need to redesign your class to have its data make more sense the way you need to use it.

Inside class access to outside class variable? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have classes: C1 and C2, a C1 instance is created inside C2, and some C1 class functions also need variables from C2. Although I can move those function inside C2, it would be a little bit messy. Is there any way to import C2's variable into the test_func in C1?
C1_class.py:
class C1():
C1_a = 1
C1_b = 2
def test_func(self):
result = self.C1_a*C2.C2_a+self.C1_b*C2.C2_b
return result
C2_class.py
import C1
class C2():
C2_a = 1
C2_b = 2
C1_sample = C1_class.C1()
C2_sample = C2()
print(C2_sample.C1_sample.test_func)
Printing the function isn't what you want, I think ... you want the functional value, correct?
print(C2_sample.C1_sample.test_func() )
# ^^ forgot the parentheses
Output:
5
The problem is not that they're in two different files. It's that you haven't called the function.
test_func
is the function descriptor, giving you access to that object.
It's attributes include the parameters, etc.
test_func()
is a call to the function, returning a value.

Designing a black box python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to have a black box in python where
The input is a list A.
There is a random number C for the black box which is randomly selected the first time the black box is called and stays the same for the next times the black box is called.
Based on list A and number C, the output is a list B.
I was thinking of defining this black box as a function but the issue is that a function cannot keep the selected number C for next calls. Note that the input and output of the black box are as described above and we cannot have C also as output and use it for next calls. Any suggestion?
Make it a Class so C will persist.
class BlackBox():
def __init__(self):
self.C = rand.randint(100)
etc...
As a side note, using some pretty cool Python functionality...
You can make objects of this class callable by implementing __call__() for your new class.
#inside the BlackBox class
def __call__(self, A):
B = []
#do something to B with A and self.C
return B
You can then use this in your main code.
bb = BlackBox()
A = [1, 2, 3]
B = bb(A)
the issue is that a function cannot keep the selected number C for next calls.
This may be true in other languages, but not so in Python. Functions in Python are objects like any other, so you can store things on them. Here's a minimal example of doing so.
import random
def this_function_stores_a_value():
me = this_function_stores_a_value
if 'value' not in me.__dict__:
me.value = random.random()
return me.value
This doesn't directly solve your list problem, but it should point you in the right direction.
Side note: You can also store persistent data in optional arguments, like
def this_function_also_stores_a_value(value = random.random()):
...
I don't, however, recommend this approach because users can tamper with your values by passing an argument explicitly.
There are many ways to store persistent data for a function. They all have their uses, but in general, the ones that come first are useful more often than the ones that come later. (To keep things shorter, I'm solving a slightly simpler problem than the one you asked about, but it should be obvious how to adapt it.)
Instance attribute
class BlackBox:
def __init__(self):
self.C = rand.randint(100)
def check(self, guess):
return (guess - self.C) / abs(guess - self.C)
Now you can create one or more BlackBox() instances, and each one has its own random number.
Closure variable
def blackbox():
C = rand.random()
def check(guess):
return (guess - C) / abs(guess - C)
return check
Now, you can create one or more check functions, and each one has its own random number. (This is dual to the instance variable—that is, it has the same capabilities—but usually one or the other is more readable.)
Global variable
def makeblackbox():
global C
C = random.randint(100)
def check(guess):
return (guess - C) / abs(guess - C)
This way, there's only a single blackbox for the entire program. That's usually not as good a design, which is one of the reasons that "globals are bad". Plus, it's polluting the global namespace with a C variable that means nothing to anyone but the check function, which is another one of the reasons that "globals are bad".
Function attribute
def makeblackbox():
check.C = random.randint(100)
def check():
return (guess - check.C) / abs(guess - check.C)
This is equivalent to a global in that you can only ever have one black box, but at least the variable is hidden away on the check function instead of polluting the global namespace.
Class attribute
class BlackBox:
C = rand.randint(100)
#staticmethod
def check(guess):
return (guess - BlackBox.C) / abs(guess - BlackBox.C)
This is again equivalent to a global variable without polluting the global namespace. But it has a downside over the function attribute—you're creating a class that has no useful instances is often misleading.
Class attribute 2
class BlackBox:
C = rand.randint(100)
#classmethod
def check(cls, guess):
return (guess - cls.C) / abs(guess - cls.C)
This is different from the last three in that you can create new blackboxes by creating subclasses of BlackBox. But this is very rarely what you actually want to do. If you want multiple persistent values, you probably want instances.
Since you are asking in the comments.
This is probably not recommended way but it's easy and works so I'll add it here.
You can use global variable to achieve your goal.
import random
persistant_var = 0
def your_func():
global persistant_var
if persistant_var:
print('variable already set {}'.format(persistant_var))
else:
print('setting variable')
persistant_var = random.randint(1,10)
your_func()
your_func()
Output:
setting variable
variable already set 7
Hope this is clear.

Python: calling def from a different def [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am relatively new to Python and I've been stuck on something that seems very trivial, so hoping someone can help.
What I'm trying to do is call a method inside a method in Python. I want to call this method several times, in various different methods, so I don't want to have to keep on copying and pasting the code if I'm going to be using it ~10 times - just to keep calling that "def".
I have tried things such as:
return anotherMethod()
Any ideas how to do this?!
Thanks!
Edit:
Sorry about the vagueness of the question. I'm trying to get my head around the terminology.
def scaleC():
pianoIcon = Icon("PianoScaleC.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
return piano()
def scaleCS():
pianoIcon = Icon("PianoScaleCS.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
return piano()
def piano:
#play the piano keys, etc
So you are doing something like this?:
def my_global_function():
def my_local_function():
print('hello world')
my_local_function()
And then outside of that definition you want to call that function again?
But it has been destroyed because you exited the scope.
You can make it a global then:
my_local_function_global_scope = None
def my_global_function():
def my_local_function():
print('hello world')
# Declare variable space as global and assign to it
global my_local_function_global_scope
my_local_function_global_scope = my_local_function
my_local_function()
my_local_function_global_scope()
SO you want to call the same function/method ten times? Do it in a loop eh?
for i in range(10):
print('Iteration Number %s' % i)
anotherMethod()
if you want to return the results of the function ten times in a list, you can use list comprehension
return [anotherMethod() for _ in range(10)]
Note: the _ variable is a convention used when you are required to have an assignment but you do not want to store that variable, naming it _ will effectively delete it as I understand.
my last idea is that you wan to reference the callable once and call it ten times. You can do that too (And its one of my favorite things about python)
my_method = anotherMethod
my_method()
my_method()
...
my_method()
my_method()
If you are asking on how to define methods in Python that can be called from everywhere you can write the method you want on a library.py file like this:
def fun(a , b):
return a + b
and then call it from another file (ie. program.py) like this:
from library import fun
def main():
# your code
print fun(1, 2)
a = 4
b = 5
c = fun(a, b)
print c
if __name__ == '__main__': main()
this will output:
3
9
hope that helps.
Well it is quite simple. You just literally call that function inside your other function. Here is an example:
def Examples():
print 'Function successfully called!'
def Example()
print 'Calling function...'
Examples() #This will call the function above it
Example()
Your result should be:
Calling function...
Function successfully called!
No errors should pop up and this should work. Just add a variable:
loop = 0
and put the functions in a while loop:
while loop <> 10:
loop += 1
def Examples():
print 'Function successfully called!'
def Example()
print 'Calling function...'
Examples() #This will call the function above it
Example()
This will should solve your problem. I hope this helps you! Your final code with this implied should be:
loops = 0
while loops <> 10:
loops += 1
def scaleC():
pianoIcon = Icon("PianoScaleC.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
piano()
def scaleCS():
pianoIcon = Icon("PianoScaleCS.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
piano()
def piano:
#play the piano keys, etc
If I understand your question right, you just need to use it like this.
class YourClass(object):
def method(self):
pass # here goes your method
def method_where_i_want_to_use_other_method(self):
self.method()
#other things you need in this method

How should I call functions defined outside of the main function?

So I'm fairly new to python and I am working on an algorithm and I have let's say 2 functions
func1(x)
func2(x)
already defined outside the main function.
Now I want to call these functions inside the main functions one nested inside the other
Something like this
def funcmain(func1(func2(x)))
It obviously is not working I haven't been able to get it work anyway I want. Any tips on this?
Edit: What I meant to do is that I want to input a string, I want it to go through func2 first, then the return value from func2 to go through func1 and finally the return value of func1 to go through func main. I have tested each function separately and they are working as intended but I can't seem to get them interlinked together
I hope this code snippet will help to clarify things for you.
#!/usr/bin/python
def func1(x):
return x + 1
def func2(x):
return x + 2
def main(x):
print func1(func2(x))
if __name__ == '__main__':
main(0)
The output is 3.
Is this what you mean? Your question is not too clear. I assume x is also defined globally somewhere.
def funcmain():
return func1(func2(x))
take the following functions:
def func1(x):
return x+1
def func2(x):
return x*2
by itself you COULD do this: func1(func2(3)) which would return 3 times 2 plus 1. This works because by itself func1(func2(3)) actually returns a value, not a function.
BUT since you are trying to put it as the basic argument for the main function like this:
def main(func1(func2(x))): #dont do this, this is what you did, it is bad
return x*3
its not going to know what to do with that because there is no default for x...
you CAN DO THIS THOUGH:
def main(x=func1(func2(1)):
return x*3
this would do the appropriate math to 1 and then assign it as x (Because as we saw earlier, func1(func2(3))` would return THE RESULT OF FUNCTIONS not a function itself, then multiply it by 3. since you are defaulting x to equal a value ( which is func1(func2(1))
This is bad practice still, because you are defaulting to whatever func1(func2(1) comes out to.
what you probably want in the end is something simpler:
def main(x):
y = func1(func2(x))
return y*3
or maybe even simpler than that
def main(x):
return x*3
#and then just call it like this
main(func1(func2(1))

Categories

Resources