How to call a class's method 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 8 years ago.
Improve this question
I'm new to python and trying to write a python script that would take two command line arguments, do something to them, and return the output back to the stdout.
My script is like this:
class MyClass:
def GET(self):
#get the passed in arguments in arg1 and arg2
return self.perform(arg1, arg2)
def perform(self, arg1, arg2):
return arg1+arg2
if __name__ == "__main__":
#call the GET method of MyClass with all the arguments
How can I pass the command line arguments sys.argv[1:] to GET method of MyClass?
Will the signature of GET change from GET(self) to GET(self, arg1, arg2)?

What you've written there is instance methods, which need an instance for you to call them on.
E.g.
x = MyClass() # create an instance of MyClass
x.GET()
However, arg1 and arg2 are never initialised, so your GET method won't know what they are. If you want to pass them into GET you would need to specify them as parameters:
class MyClass:
def GET(self, arg1, arg2):
...
and then you could call the method with
x.GET(sys.argv[1], sys.argv[2])
but that would make GET kind of pointless, since all it does is redirect the call to the perform method.
If you prefer, you could pass the argv array itself to GET. That would require:
class MyClass:
def GET(self, args):
return self.perform(args[1], args[2])
...
x = MyClass()
x.GET(sys.argv)
If you want to output the result to stdout, you would use print. E.g.
print(x.GET(sys.argv))

Related

How to write and call wrapper without decorator in python [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 20 days ago.
This post was edited and submitted for review 20 days ago.
Improve this question
I'd like to write wrapper function for various functions.
How can I write the wrapper function and call it?
Without decorator
This is my expectation but doesn't work.
import external_library # example
def wrapper(func):
return func()
def test1(a,b):
print(a,b)
def test2(a,b,c,d):
print(a,b,c,d)
wrapper(test1(1,2)) # a,b
wrapper(test2(1,2,3,4)) # 1,2,3,4
wrapper(external_library.some_api()) # working like direct call
I got an error
'NoneType' object is not callable
wrapper() takes a function as an argument. Just add some lambda keywords and it should work:
one = wrapper(lambda: some_api.request_one(1,2,3,4,5))
If you want to wrap methods of a class you are importing from a library, you will need to instead write a new class inheriting from the library class. Then you will only need to write overrides for the methods you want to wrap, where you just add your wrapper code, and then call super().method()
So lets say you want to override method test on class Foo from library bar to print the time to execute, you could do the following
import time
from bar import Foo
class Baz(Foo):
def test(self, x):
start = time.time()
super().test(x)
end = time.time()
print(f"Foo.test() time to execute : {end - start}")
A = Baz()
A.test(5)
# Output: Foo.test() time to execute : 0.135
In all other ways, an instance of Baz will act as an instance of Foo

Calling a function from an other function in the same class without passing self [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 12 months ago.
This post was edited and submitted for review 12 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Let's say in my class, I have a callback function from a library (python-telegram-bot). Within that callback function I have to call another function in the same class. I can't modify the arguments in the definition of the callback and add 'self'. What is/are the proper ways to do call that second function without passing 'self'?
class MyClass():
def other_function(arg):
print (arg)
def new_member(update: Update, context: CallbackContext):
other_function(arg_value)
new_member_handler = MessageHandler(Filters.status_update.new_chat_members, new_member)
dispatcher.add_handler(new_member_handler)
You should define the method with a self argument before the arguments that the library provides.
class MyClass():
def callback_function(self, arg1, arg2):
print(arg1)
self.other_function(arg2)
def other_function(self, arg2):
print(arg2)
Then when you're registering the callback, use instance.callback_function (where instance is an instance of MyClass that you created) to provide a method that's bound to that instance.
Or if the method doesn't need to use self, you can declare with #staticmethod. Then use MyClass.callback_function when registering.

Using self and parameters in a Python Script [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'd like to use self (for global variables) and the parameters from the command-line in my Python Script but can't really get them to work.
def otherFunction(self)
print self.tecE
def main(argv,self):
self.tecE = 'test'
otherFunction()
if __name__ == "__main__":
main(sys.argv[1:],self)
This gives me an error:
main(sys.argv[1:],self)
NameError: name 'self' is not defined
So how and where to define self?
Usually the python convention of self is to be used in python classes, you did a bit of a mess.
So either you are not using classes and treating self just as a global dict, like this:
import sys
myglobal = {} # Didn't want to name it self, for avoiding confusing you :)
def otherFunction():
print myglobal["tecE"]
def main(argv):
myglobal["tecE"] = 'test'
otherFunction()
if __name__ == "__main__":
main(sys.argv[1:])
Or writing a class, like this:
import sys
class MyClass():
def otherFunction(self):
print self.tecE
def main(self, argv):
self.tecE = 'test'
self.otherFunction() # Calling other class members (using the self object which actually acting like the "this" keyword in other languages like in Java and similars)
if __name__ == "__main__":
myObj = MyClass() # Instantiating an object out of your class
myObj.main(sys.argv[1:])
So how and where to define self?
You will use self:
As the first argument of your class methods def my_method(self, arg1, arg2):
Within the class to refer to any other class members (just as demonstrated above) self.do_job("something", 123)
For creating class members: self.new_field = 56 Usually in __init__() constructor method
Note: decalring a class variable without the self.new_var, will create a static class variable.

Change what is returned on screen by class instance [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
Lets say I have a class Hello, and I do the following:
>> a = Hello()
>> a
This will return the following:
<__main__.Hello instance at 0x123abc>
How do I change the class to return something else (like an instance variable for example)?
add:
class Hello(object):
def __str__(self):
return "HI"
def __repr__(self):
return "Hi"
>>> a = Hello()
>>> a --> calls __repr__ method
Hi
>>> print a --> calls __str__ method
HI
In the interest of answering the EXACT question being asked, what you're asking about, "change what's returned by calling a class", is roughly the semantics of a metaclass.
So, for the sake of argument, lets suppose we want to have a class that looks like this:
class Foo(object):
__metaclass__ = MyMeta
def __init__(self, bar):
print "Hello from", self
self.bar
actually satisfy:
>>> myBar = object()
>>> myFoo = Foo(myBar)
Hello from <__main__Foo object at 0x...>
>>> myFoo is myBar
True
Specifically, we have a real class, which really gets instantiated when called upon, but the return value is something else, we can do that, so long as MyMeta looks about like so:
class MyMeta(type):
def __call__(cls, *args, **kwargs):
self = super(MyMeta, cls).__call__(*args, **kwargs)
return self.bar
Of course, I would not do this.

Import class in same file in Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to python and I have a file with several classes. In a method in the class "class1" I want to use a method from another class "class2". How do I do the import and how do I call the method from class1? I have tried several different things but nothing seems to work.
You don't need to import them, because they are already in the same file.
Instead, do something like this:
class1 = Class1() #assigns class1 to your first class
Then call a method inside of Class1 like this:
Class2():
def method2(self):
class1.method1() #call your method from class2
Basically you are taking Class2() and pointing it to the instance class2, then you are calling a method of that class by doing class2.method2(). It's just like calling a function from the current class, but you use instance name in front of it.
Here is an example:
class Class1():
def method1(self):
print "hello"
class Class2():
def method2(self)
class1 = Class1()
class1.method1()
Then, when you call Class2() it will print 'hello'.
Let's say your file with all the classes is called myclass.py with the following:
class Class2(object):
def foo(self):
return 'cabbage'
class Class1(Class2):
def bar(self):
return self.foo()
In your main script, you can import the module as usual:
import myclass
And now you can create an instance of class1:
myinstance = myclass.Class1()
Then you can call the function directly:
myinstance.bar()
# Returns 'cabbage'
If all of the classes are in the same file, you don't need to import them. They are in the module scope already. Here's an example:
class A():
def print_one(self):
print "one"
class B():
def print_two_and_one(self):
print "two"
A().print_one()
B().print_two_and_one()

Categories

Resources