How do you call a method from a class? [duplicate] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What does "call" mean and do? How would you "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:
def add(a,b):
return a + b
you would call the function like this:
add(3,5)
which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:
answer = add(4,7)
Which would set the variable answer equal to 11 in this case.

I'll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be "dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have."
Calling a function/class instance in Python means invoking the __call__ method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__ method. The same applies for new-style classes, except there is no notion of "instance" with new-style classes. Rather they are "types" and "objects".
As quoted from the Python 2 Data Model page, for function objects, class instances(old style classes), and class objects(new-style classes), "x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...)".
Thus whenever you define a function with the shorthand def funcname(parameters): you are really just creating an object with a method __call__ and the shorthand for __call__ is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.
For now I suggest reading the Official Python Tutorial.

To "call" means to make a reference in your code to a function that is written elsewhere. This function "call" can be made to the standard Python library (stuff that comes installed with Python), third-party libraries (stuff other people wrote that you want to use), or your own code (stuff you wrote). For example:
#!/usr/env python
import os
def foo():
return "hello world"
print os.getlogin()
print foo()
I created a function called "foo" and called it later on with that print statement. I imported the standard "os" Python library then I called the "getlogin" function within that library.

when you invoke a function , it is termed 'calling' a function .
For eg , suppose you've defined a function that finds the average of two numbers like this-
def avgg(a,b) :
return (a+b)/2;
now, to call the function , you do like this .
x=avgg(4,6)
print x
value of x will be 5 .

Related

The name and nature of the "hidden" builtins classes object, function, code etc [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 2 years ago.
Improve this question
I am very curious about the classes that exist in the module builtins that are not accessible directly. Such as
type(lambda: 0) # __name__='function' of __module__='builtins'
type((lambda: 0).__code__) # __name__='code' (aka. bytecode) of __module__='builtins'
None.__class__ # __name__='NoneType' of __module__='builtins'
And the matriarch:
str.__mro__[1] # # __name__='object' of `__module__` 'builtins'
traceback as passed to the __exit__ magic method of a context manager is the same:
def __exit__(self, exc_type: Exception, exc_value: str, exc_traceback: 'bultins.traceback'):
pass
(The module traceback is a module and simply shares the name, ditto for tracemalloc.Traceback). In the above the object name is a string, but this is a rare example of a "hidden" builtins class and typehinting because for a function instances typing.Callable does the job.
Q: what is the name for these "hidden" builtin classes?
I understand that the builtins are written in C in CPython. I had a quick gander at the CPython Github repo and I could not figure out why unlike tuple they are "hidden". I use the word "classes" as they have the same magic methods etc. and work like other classes:
NoneType() == None # True as expected
bytecode = code(...) # bytecode...
fxn = function(bytecode)
Q: Is there a PEP reason why they are not in builtins?
If it is simply to stop namespace pollution, I'd have though they'd be underscored objects in the builtin module say or in some module... unless they are somewhere else
Q: Can they be imported directly by somewhere else?!
Maybe as an answer to reasoning – afaik, this is about not providing public API that goes agains semantics.
I.e. instantiating NoneType is something that you rather should not do, same as doing equality comparison for None.
If you have specific needs to build something dynamically – please provide them, usually there's an official API to do so (ast, as an example)

Python variable inheritance not working (as expected) [duplicate]

This question already has answers here:
How to create dynamical scoped variables in Python?
(4 answers)
Closed 2 years ago.
Why, in this code, can't I access db or file from inside do_more()?
def do_stuff(queue):
db = getDbConn()
while True:
file = queue.get() #DirEntry object
...
do_more(otherObject)
q.task_done()
I'm aware I could pass db and file as arguments to do_more(), but I feel like those variables should just be available in functions called from other functions. It works that way from main to first level functions. What am I missing here?
In the code you provided, you don't even attempt using the variables from do_stuff.
But as a general rule, you should be able to use variables from a parent function inside a child function, either by passing them as variables or by using them when initializing the child function, like this:
def foo():
foo2 = "foo"
def bar():
print(foo2)
bar()
foo()
If i did not answer your question let me know.
no , you cant access those variables , I know what you think , which is wrong.
you can access variables inside loops and if statements, not here.
imagine you have a function which is used in many different places, in that case you have access from this function to many variables which makes things complicated.
functions should be stand-alone objects which take some arguments do stuff and return something.so inside a function scope you can only see variables which are defined there and the arguments passed from the parent function using parenthesis.

choosing between a class or function in edge programming case [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Sometimes when writing python software I end up in a situation in which I am not sure whether to use a function with sub functions, or just a class. In these cases, I have a series of distinct inputs, I want to apply some transform to them and then produce a distinct output. And I don't much care about any of the variables that are created in the process of going from inputs to outputs. So it feels like it should be a simple function in this sense rather than a Class. But for these cases, its also quite a complex series of operations that are involved, often with a need for sub functions that are only useful in the process of transforming the inputs to outputs and not in any more general sense.
And at the end of the day, I usually just want to call it using:
output = my_function(input)
So I can do something like
def my_function(input):
def subfunc1(blah):
return blah1output
def subfunc2(blah):
return blah2output
#lots of complex code here that calls subfunc1 and subfunc2
return output
But then co-worker X might come along and say, wow that looks like a pretty complex function, you should use a class! OR I could do this
class my_function(object):
def __new__(self, input):
#lots of complex code here that calls subfunc1 and subfunc2
return output
#staticmethod
def subfunc1(blah):
return blah1output
#staticmethod
def subfunc2(blah):
return blah2output
But, this seems to be like an odd use for a class because I don't really care about creating and maintaining instances of the class.
A major advantage of using classes here though is that you can more easily test subfunc1 and subfunc2 and this alone might be sufficient reason to use one.
However, as I'm still new to programming can someone suggest the best possible solution for a production environment and/or the solution that is generally most pythonic?
#wwii's comment is the right answer.
To elaborate, you are correct in your intuition that it might not be pythonic to create a class that will function as a singleton - modules are the preferred way to do this (here's an oblique reference in the programming faq).
You are also correct that it is good to be able to test your subfunctions. One other reason to pull them out of the function body is because Python, as an interpreted language, will otherwise rebuild the subfunction inside every time that your outer function is called.
Benjamin Gleitzman's glorious howdoi module (the link is to his github repo) is a beautiful example of how to break out a complex problem into small, very readable pieces -- following the PEP 8 philosophies that "flat is better than nested" and "simple is better than complex"
edit
Here's an example of a simple module (python tutorial on modules) that can mask your internal functions. The structure is:
mymodule
|____
|___ __init__.py
|___ submodule.py
in __init__.py:
"""
This docstring shows up when someone does `help(mymodule)`.
"""
from submodule import my_function
in submodule.py:
def _subfunc1(x):
"""A preceding underscore signals to the reader that it's an internal function."""
return x + 1
def _subfunc2(x):
return x * 2
def my_function(x):
"""Yours will be cooler."""
return _subfunc1(x) * _subfunc2(x)
And to use it:
>>> import mymodule
>>> result = mymodule.my_function(5)
>>>
>>> # But internal functions (not imported) won't be visible...
>>> mymodule._subfunc1(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '_subfunc1'

How can I forward-declare/prototype a function in Python? [duplicate]

This question already has answers here:
Does Python have class prototypes (or forward declarations)?
(6 answers)
Closed 8 years ago.
How do I prototype a method in a generic Python program similar to C++?
# Prototype
# Do Python prototyping
writeHello() # Gives an error as it was not defined yet
def writeHello():
print "Hello"
Python does not have prototyping because you do not need it.
Python looks up globals at runtime; this means that when you use writeHello the object is looked up there and then. The object does not need to exist at compile time, but does need to exist at runtime.
In C++ you need to prototype to allow two functions to depend on one another; the compiler then can work out that you are using the second, later-defined function. But because Python looks up the second function at runtime instead, no such forward definition is needed.
To illustrate with an example:
def foo(arg):
if not arg:
return bar()
def bar(arg=None):
if arg is not None:
return foo(arg)
Here, both foo and bar are looked up as globals when the functions are called, and you do not need a forward declaration of bar() for Python to compile foo() successfully.

Understanding "def main" and "overloading" in Python [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I often see some code with
def main(A,B)
some steps
described as an "overloading for the main function", after reading something more specific about Python I know that this is not true because:
Python is a loseless type language
a function/method in Python doesn't even know the type for a given parameter, nor python cares
I'm also not sure if there is a real distinction between instances and "static methods" or "class methods", probably they are the same thing and the only difference is given by the use of decoratos, but this is probably related to my first approach to a functional language after spending so much time with C/C++ .
Even more, in Python, the first indentation level is used as an entry point ( like main() in C/C++ ), so I don't get why you should define a main at an indentation level that is different from the really first one.
The general idea that I have about Python's keywords is that the keywords have a special semantic value rather than a real defined syntax ( probably it's because the C++ is less "idiomatic" , I don't really know how explain that ), they are used as a placeholder for something and they give a special meaning to the section where they are applied. There also special variables like __name__ that are there just to store special informations and nothing more.
After all this small bits of information stored in my brain I still dont' get the real meaning of the first code example:
what is special about the main() function ?
what is the point of defining something like a "main" function if it's not real "main"
how Python decide what function is the one to call if it's not typed ?
there is a difference between how the interpreter reads __init__.py files and other files ?
To answer your questions:
main() function
Nothing is special about it. You have to call it yourself, by doing something like:
def main():
print "This is main"
if __name__ == "__main__":
main()
Why use main()
The reason you might do that is to keep your main entry-point code together in a convenient way. For instance, if you create some variables in main(), they won't be global variables, which avoids polluting the global namespace. It also prevents the main() function from being run if you import the module from another (instead of running it directly as a script). This can be useful if you don't want to do some initialization (e.g., print messages) when importing, but you do want to do them when running as a standalone script.
How does Python decide which function to call
Python does not support "overloading" in this sense. There can only be one function with a given name in a given namespace. If you make a second function with the same name (or second method with the same name in the same class), you overwrite the first one completely.
__init__.py
This question is not really related to your others. But no, it doesn't process them in a different way. It processes them at a different time (when you import a package, rather than a module in a package), but the code in them is run just the same as the code in any other Python file.
main() in python is just a function name. The common idiom
if __name__ == '__main__':
#do something
is a shortcut to figure out of the code in this file is being run as a program rather than imported as a module.
Because python is intended to by type-free, the community puts a strong emphasis on conventions and best practices. This doesn't provide the same level of predictability as a compiler, but it helps keep the chaos at bay. Readability is a core python value and idioms like this provide valuable structure.
Python does not support function overloading in the sense that other languages do. In strongly typed languages you might write multiple versions of the same function with the same name but varying input arguments:
void DoSomething (int a) {};
void DoSomething (float f) {};
void DoSomething (string s){};
In python there is no equivalent idiom. In most cases it's unneeded: for a numeric operation you don't really care if the incoming numbers are floats, ints or whatever -- only that they support the correct operators. This is where the python mantra of 'duck typing' comes in - if it walks like a duck and quacks like a duck, it's a duck. So python functions idiomatically look for functions or operators on incoming arguments rather than checking their types.
As for instance vs static methods:
In python every instance method implicitly gets the owning instance as the first argument to a function:
class Test(object):
def __init__(self, arg):
self.variable = arg
def example(self):
print self.variable
fred = Test(999) # note: no 'self' passed here
fred.example()
>>> 999
joe = Test(-1)
joe.example()
>>> -1
a class method gets the class type, rather than an instance, as the implicit first argument. Class methods can see class-level variables, which are defined in the class scope rather than in the instance scope - but they don't know anything about a particular instance.
class TestCls (Test)
CLASS_VARIABLE = "hello"
# other behavior inherited from Test
#classmethod
def class_example(cls):
print cls.CLASS_VARIABLE
barney = TestCls(123)
barney.example()
>>> 123
barney.class_example() # again, no explicit class passed in
>>> 'hello'
a static method gets no implicit arguments at all:
class TestStatic (TestCls):
CLASS_VARIABLE = 'goodbye'
# inherited stuff again
#staticmethod
def static_test():
print "behold, I have no implicit argument"
Static and class methods also don't need an instance to be called:
wilma = TestStatic(123)
wilma.static_test() # you can call from an instance
>>> behold, I have no implicit argument
# or not:
TestStatic.static_test()
>>> behold, I have no implicit argument
TestStatic.class_example()
>>> goodbye # the method is inherited, but the class variable come from this class

Categories