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
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 9 months ago.
Improve this question
In (some) python libraries, when i look up the code, i see a bunch of functions or class methods which are written like this:
def funcName():
pass
I just want to know how those functions DO stuff even though they only have pass which means that the function should do nothing.
For user-defined functions, pass means doing nothing, but for some library functions (including third-party libraries), they usually mean that their logic is not written in pure Python code, such as NumPy and Python standard library, in order to pursue efficient operation, most functions are written in C language, and provides the corresponding Python interface.
More detailed answer
Functions in python syntactically can't be empty. That's why you need to populate them, usually with pass
Sometimes, functions are declared, but purposely left empty. Then, they can be used in the default implementations, but possibly overridden by classes extending (inheriting) the library class.
Those functions/methods with just the pass statement do nothing in particular. pass is usually a placeholder for code that will be written later.
You can also find the pass statement in classes that define custom exceptions, for instance:
class MyException(Exception):
pass
Usually these are place holder methods in a (possibly abstract) base class that define a template for derived classes.
pass does nothing. It's a filler to let the code run before you implement something. The libraries are probably using pass to:
Leave blank code to finish later
Create a minimal class:
Imply that a section of code does nothing
Loop forever (and do nothing)
So to your question about libraries, they probably do nothing. pass on its own is almost as good as a blank line, but can be mixed with functional statements to achieve a working module. But the function in your question does nothing at all.
Say I wanted to keep a function f in my file, and come back to it later. I could use pass to avoid IndentationError:
>>> def f():
... pass
...
>>> f()
>>>
As without pass, I'd have:
>>> def f():
...
File "<stdin>", line 2
^
IndentationError: expected an indented block after function definition on line 1
>>>
This is also explained in the offical docs:
The pass statement does nothing.
It can be used when a statement is required syntactically but the program requires no action. For example:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
Python pass is an empty statement to maintain the integrity of the program structure. Pass does not do anything and is generally used as a placeholder statement. Nothing happens when the pass is executed. It results in no operation.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 2 years ago.
Improve this question
Is hasattr() a method? It does take an object instance as a parameter, but it is not used as object.hasttr(). I would say it is not a method then?
Everything in Python is an object, even functions and methods. So the fact that hasattr() takes an object is nothing special, so do str() and input() and sum().
A method is a function that has been bound to an object by accessing it as an attribute; so "foo bar".split gives you the bound str.split method:
>>> "foo bar".split
<built-in method split of str object at 0x7f84bef6a730>
This one happens to be “built-in” because it is implemented as part of the Python runtime, but it’s no different from a function on a class written in Python.
Calling it returns the result of the method as applied to the string it is bound to:
>>> method = "foo bar".split
>>> method()
['foo', 'bar']
I can also use it directly, unbound:
>>> str.split("spam ham")
['spam', 'ham']
hasattr() is not bound. It's a function. You can't bind it like you could with Python functions even if your tried*.
Python functions, added to a class, become methods automatically when you access them as an attribute on an instance of the class:
>>> class KnightsWhoSayNi:
... pass
...
>>> def speak(self): return "Ni!"
...
>>> speak
<function speak at 0x10fe65f28>
>>> knight = KnightsWhoSayNi()
>>> hasattr(knight, "speak") # using that function you mentioned!
False
>>> KnightsWhoSayNi.speak = speak # adding the function to the class
>>> knight.speak # now it exists! As a method...
<bound method speak of <__main__.KnightsWhoSayNi object at 0x10fe71080>>
>>> knight.speak()
'Ni!'
Note how speak() was given an argument named self, but I didn't have to pass it in. Because the method is bound to a specific instance of the class, that's taken care of automatically. The first argument passed in is the instance. The name doesn't even matter, but self is the convention, best stick to that.
As an exercise, you could try the above example yourself. Then try adding hasattr to the class. You'll find that you cant use it like a method, it won't become bound via knight.hasattr`, the instance won't be passed in as the first argument, you will still have to pass in two arguments for it to work at all.
If you wanted to go off the deep end, you could learn about how binding works in the Python Descriptors HOW-TO. Don’t worry if that feels too big of a step, that’s quite advanced.
* To pre-empt not-picking: You can emulate binding by using functools.partial() or functools.partialmethod(), but that’s not quite the same thing.
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 5 years ago.
Improve this question
A bare-bones example of a decorator is:
def strong(func):
def wrapper():
return '<strong>' + func() + '</strong>'
return wrapper
#strong
def greet():
return 'Hello!'
wrapper is an entitled name for the 'inside first-order-function' inside the Higher-Order function strong.
My question is that the word wrapper has no real meaning except to confuse newbie. Why not use 'adder', because it can be discerned intuitively?
Decorator pattern - Wikipedia
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.[1]
The keyword in Wikipedia's explanation is 'added'.
And in Cambridge English Dictionary:
to add something to an object or place, especially in order to make it more attractive:
The keyword is also 'add'.
So why is wrapper better than 'adder'?
When you use a decorator, you've wrapped your original code in another function, making the original function invisible. To continue your example,
def strong(func):
def wrapper():
return '<strong>' + func() + '</strong>'
return wrapper
#strong
def greet():
return 'Hello!'
def weak_greet():
return 'hi'
print(greet)
print(weak_greet)
If you run this, you get the following output.
<function strong.<locals>.wrapper at 0x000000000129A268>
<function weak_great at 0x000000000129A2F0>
When you used the decorator, you took your function, created a new function that wrapped code around your old function and returned that new, anonymous, function.
You can see some unpleasant effects if you try to pickle it.
if you do pickle.dumps(weak_greet), you get b'\x80\x03c__main__\nweak_great\nq\x00.'. but if you try to pickle.dumps(greet), you get AttributeError: Can't pickle local object 'strong.<locals>.wrapper'. (dealing with decorated classes and functions that must be pickled is one of the circles of hell I don't wish to revisit any time soon).
You are not adding to your function. You are wrapping your original function in a shiny new function. That new function says, "There's something I'm hiding in here and I won't tell you what it is (functools.wraps can sometimes help with this, as it would in your case). But, when you give me input, I'll alter it like so (or not at all), pass it to my secret function, (possibly) alter the output and give you that. Your original function is inaccessible (hence pickle's confusion).
NOTE: You can re-create the look of your original function by further wrapping your wrapper with #functools.wraps(original_function), which does not affect output, but wraps everything in a box to make it look exactly like the original function. so,
from functools import wraps
def strong(func):
#wraps(func)
def wrapper():
return '<strong>' + func() + '</strong>'
return wrapper
would now look like your original function and be pickle-able. It would be like wrapping a surprise present, and then wrapping the present again with wrapping paper that told you (in great detail) what the surprise was.
This question already has an answer here:
python string module vs str methods
(1 answer)
Closed 6 years ago.
I am new to programming therefore may sound idiotic. I am learning python where I am not able to understand how few methods like upper(), split() etc work.
I mean you directly use like below:
"ABC".upper() or "abc,xyz".split(",")
Or, you can first import string and then call these methods like below:
import string
string.upper("abc")
string.split("abc,xyz", ",")
What is the difference, and how would we import string module when we can achieve the same output without importing it.
Are there similar cases exist apart from string module?
In fact, one of the paradigm you can use in Python is the Object Oriented Programming, where you modify object state through "methods" like this: myobject.mymethod().
Syntactically, it means that the first argument of the method mymethod() is in fact the object itself. But, as Python want also to deal with other paradigms (functional programming, imperative programming, and so on), there is two syntactical ways to address this method.
One is simply as I mentioned before: myobject.mymethod(), and the other one is simply to consider that the first argument is the object itself: mymethod(myobject).
More precisely, you can realize that when you define by yourself a method because you have to specify the first argument by self which is a reference to the object itself like this:
def mymethod(self):
pass
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 don't know what type it is. How do I check and print it out to console?
a type is basically a value kind and operations that are valid on that value
type(object) #gives you the type
if you want to test for a type
import types
class foo(object):
pass
>>> foo is types.ClassType # test if foo is a class
True
Call the type() function. See the types module for a list of type names you can use with type().
type(variable) will tell you what type something is.
While you can use type() to perform introspection I have to wonder what you're really trying to accomplish.
In Python it's considered to be far better practice to focus on object behavior ... API ... than on type.
Do you care if the object at hand is a Foo() ... or will some subclass of Foo() or some sort of proxy for Foo() (some object containing a Foo()-like object and delegating the requisite functionality to it) do?
The usual advice I see is to use Python's exception handling ... try to use the desired interfaces as if the object is of the correct type and be prepared to handle the exceptions that may be thrown if the object doesn't support that usage. (Most often that will be a TypeError or AttributeError, of course).
Another option is judicious use of hasattr() to see if the object has the necessary attributes (usually methods) to be used like the desired object. (The main caveat there is that there may be method name collisions with completely incompatible semantics in unrelated classes of objects).
Recent versions of Python have introduced the support for "abstract base classes" (ABCs). This basically allows you to use isinstance() and issubclass() in a way that refers to the intended semantics of the objects being tested rather than on their literal instantiation and class hierarchical artifacts. When used with an ABC isinstance() returns a value which indicates whether class supports the signature methods that are considered definitive of the intended semantics.
You can read more about the most commonly used ABCs in the Python Docs: collections module (section 8.3.6).
Unfortunately it's possible you could still confuse the ABCs if you re-use certain method names which have a conventional meaning in the existing Python core or standard libraries.
For example if you create some UI class and define methods of .next() (perhaps to go with some hypothetical .previous()). Doing so, without further effort, would mean that a call like: isinstance(foo, collections.Iterable) would return True even though the semantics you implemented (presumably something like proceeding to the next page in your UI) are completely orthogonal to those that are intended by the collections.Iterable ABC.
I think it's possible to disambiguate by creating some other abstract base class and specifically registering your class as implementing that abstraction. However, I don't know exactly how that would work.
print object.__class__.__name__
Should do the trick.