I have a class where I want to call different modules form it, depending on an input from the user.
In my mind it would look something like this:
class Test:
def test1:
print("Hello world")
def test2:
print("farewell world")
user = input("> ")
Test.f{user}
Where it now will call what the user has told it to, but it doesn't work.
So my question is if it's possible, if it is then how I would accomplish it.
When trying examples from the given link, I keep encountering a problem for example where it tells me
"TypeError: test1() takes 0 positional arguments but 1 was given"
when the input looks like so:
getattr(globals()['Test'](), 'test')()
this is not the only one, and all I have tried leads to problems.
leading me to believe that either my problem is different, or I'm implementing it wrong.
Help with either scenario is much a appreciate.
You should try using getattr().
for example:
class Test:
def test1():
print("Hello world")
def test2():
print("farewell world")
userinput = input('Which function do you wish to call?\n')
# getattr() takes 2 parameters, class name, and attribute name.
myfunc = getattr(Test, userinput)
myfunc()
Related
Here is my class code:
class Example:
def __init__(self):
self.parameter1 = 1
def standardFunction(self):
print("Hello")
Is it possible to initialise the Example class and make sure that every method that may be called for this particular instance will always point to the standardFunction?
For example:
ex1 = Example()
ex1.test1()
prints "Hello"
ex1.test2()
prints "Hello"
ex1.test3.test4()
prints "Hello"
ex1.test5().test6().IamBatman(42)
prints "Hello"
Basically, I would like to always have the Example.standardFunction() called, disregarding the string after the first "dot". Plus I don't know what's being put after the dot - it may be any string, int, float, or null.
Is it possible to achieve such behaviour with Python?
Yes we can achieve similar behavior in Python by overloading __getattr__. Like this,
class Example:
def __init__(self):
self.parameter1 = 1
def standardFunction(self):
print("Hello")
def __getattr__(self, name):
return self.standardFunction
class Car:
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_details(self): #SELF allows access of attributes and methods of a class
details=print((f'The make is: {self.make}, the model is: {self.model}, & the year is: {self.year}\n'))
#return details without print function works? i.w. details=rest of the line without print + return details (next line)
def read_odometer(self): #reading the value (default)
print(f'\nReading: {self.odometer_reading}')
def update_odometer(self,mileage):
if mileage>=self.odometer_reading:
print('\nReading has been changed')
self.odometer_reading=mileage
else:
print('\nCan, not change ')
def increment_odometer(self,miles):
self.odometer_reading+=miles
x.get_details() #trying to modify print(x.get_details()) which does work. Why does print need to be supplied here?
#incrementing the odometer
print(x.increment_odometer(50)) #why is this none?
I am learning classes and am confused about some aspects:
Why is "return details" line needed for method get_details()? Normally a simple function call having def f(): print('a') works, hence the confusion.
print(x.increment_odometer(50)) is None. Perhaps a function return needed in increment_odometer() method?
Confusing points having been commented in the code. Please englighten me.
Sincerely.
It my first try to realize a "little bit bigger" project in python. Thus I want to structure the whole project using different python files. I also need some global variables. The following example works, if I put everything in one file. As soon as I split in two files it doesn't work anymore. What's an elegant way to solve the problem:
class MyClass:
def call(self):
print("In Methode call")
self.check()
def check(self):
global a
if a:
print("a ist True")
a = False
else:
print("a ist False")
a = True
def methode3(self):
print("In methode 3")
if __name__=="__main__":
a=True
instanz = MyClass()
instanz.methode3()
instanz.call()
instanz.check()
This script itself works fine.
If I call it now from the following second script, I get the error that 'a'is not defined. Call of instanz.methode3() works of course.
import test
a = True;
instanz = test.MyClass();
instanz.methode3()
instanz.call()
The following check,
if __name__=="__main__":
Is only called from when the file is run by itself as opposed to being imported. Declaring the a outside this if should work as intended.
Also, to access the new variable a, use test.a.
I have this small script implementing a single class with two functions. I wanted to simply print a value that was found in the first function from the second function when I call it from outside of the class.
Problem
It seemed really simple after reading this article over self, but nothing I try seems to be working. I keep getting attribute errors:
class search:
def test(self):
self.here = 'hi'
self.gone = 'bye'
self.num = 12
def tester(self):
return "{}".format(self.here)
s = search()
s.tester()
print (s.gone)
Returns...
AttributeError: 'search' object has no attribute 'here'
Question
How can I modify this script to achieve the result I am looking for?
define 'here'
class search:
here=None
def __init__(self):
self.here='hi'
def test(self):
...
the problem is you never execute the function test(self) which initiate the variable. you can call it using s.test() before s.tester()
Sorry if the title is confusing. I'm writing a minimalist game engine, and trying to define a class called "Area" where if the player enters the area, a function defined by the user happens. For example, one could create an instance
Area(location,function) that would fire function on the player when the player enters location (for the sake of simplicity, let it be a point or something).
Note: in pseudo-python
# in init.py
...
def function(player):
kill player
deathZone = Area(location,function)
--------------------------------------
# in player.update()
...
for area on screen:
if player in area:
Area.function(player)
The point of this is that the developer (aka me) can use any function they choose for the area. Is there anyway to do this, or should I try a better approach?
Sure, this kind of thing is certainly possible. In python, everything is an object, even a function. So you can pass around a function reference as a variable. For example try the following code:
import math
def rectangle(a, b):
return a*b
def circle(radius):
return math.pi * radius**2
class FunctionRunner(object):
def __init__(self):
self.userFunction = None
self.userParams = None
def setUserFunction(self, func, *params):
self.userFunction = func
self.userParams = params
def runFunction(self):
return self.userFunction(*self.userParams)
if __name__ == '__main__':
functionRunner = FunctionRunner()
functionRunner.setUserFunction(rectangle, 6, 7)
print(functionRunner.runFunction())
functionRunner.setUserFunction(circle, 42)
print(functionRunner.runFunction())
Here you have two functions that are defined for an area, and a class called FunctionRunner which can run any function with any number of input arguments. In the main program, notice that you need only pass the reference to the function name, and any input arguments needed to the setUserFunction method. This kind of thing will allow you to execute arbitrary code on the fly.
Alternatively, you could also replace a method on your class with a reference to another function (which is what you are asking), though this seems less safe to me. But it is certainly possible. For example you could have a class like this:
class FunctionRunner2(object):
def __init__(self):
pass
def setUserFunction(self, func):
self.theFunction = func
def theFunction(self, *params):
pass
And then do this:
if __name__ == '__main__':
functionRunner2 = FunctionRunner2()
functionRunner2.setUserFunction(rectangle)
print(functionRunner2.theFunction(6,7))
functionRunner2.setUserFunction(circle)
print(functionRunner2.theFunction(42))