Why does the method what_are_you output nothing? Syntax mistake? [duplicate] - python

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 3 years ago.
In this program the output is not what I would expect:
class example(object):
def __init__(self, foo,bar):
self.foo = foo
self.bar = bar
def what_are_you():
print(foo,bar)
print("This doesn't work either")
a = example("aaa","bbb")
a.what_are_you
#should return "aaa bbb"
print(a.what_are_you)
print(a.foo,a.bar)
Instead it outputs nothing. This is the whole output:
<bound method example.what_are_you of <__main__.example object at 0x000002A9574B4710>>
aaa bbb
Process returned 0 (0x0) execution time : 0.041 s

By not including parentheses, you're printing the function object, not calling the function. To call the function, put parentheses after it.
print(a.what_are_you())
will print the value of what_are_you() (whatever is in the return statement)

As I see now, you're printing stuff, not returning stuff, so you might need to use:
a.what_are_you()
And in your function, you need to use self to get the variable:
def what_are_you(self):
print(self.foo,self.bar)
print("This doesn't work either")

Related

Is there a preferred style for creating closures in python? [duplicate]

This question already has answers here:
Function closure vs. callable class
(6 answers)
Closed 2 years ago.
Is either of the two styles preferred or more "pythonic" for creating closures (edit: "closure-like objects")?
def make_doer(closed_var):
def doer(foo):
pass # Do something with closed_var and foo
return doer
class Doer:
def __init__(self, closed_var):
self._closed_var = closed_var
def __call__(self, foo):
pass # Do something with self._closed_var and foo
The only differences I can tell are that the former is a tiny bit shorter but the second has an advantage in that the docstring for the resulting function (__call__ in the second case) is less nested/hidden. Neither seems like a huge deal, anything else that would tip the balance?
Closures have to do with maintaining references to objects from scopes that have passed, or from earlier scopes.
Here is the simplest example of the form a Closure takes:
def outer():
x=7
def inner(y):
return x + y
return inner
i = outer()

Is it possible to make a class object iterable in Python? [duplicate]

This question already has answers here:
Python: Make class iterable
(6 answers)
Closed 2 years ago.
I'm wondering if it's possible to make a class object iterable in Python (ie. a subclass of type, NOT an instance of a class).
I've tried the following code:
class Foo:
#classmethod
def __iter__(cls):
yield 1
print(next(Foo.__iter__())) # prints 1
print(next(iter(Foo))) # TypeError: 'type' object is not iterable
Turns out it's possible with metaclasses.
class Foo(type):
def __iter__(self):
yield self.baz
class Bar(metaclass=Foo):
baz = 1
print(type(Bar)) # prints "<class '__main__.Foo'>"
print(next(Bar.__iter__())) # prints "1"
print(next(iter(Bar))) # prints "1"
Thanks #DanielB for pointing me in the right direction.
This isn't possible, as it would imply that all type objects are iterable - as you stated, classes are of type type. The underlying reason for this is that the __iter__ method is looked up on the type, not the value. E.g., in:
for i in Foo:
print(i)
Python will look up type(Foo).__iter__, not Foo.__iter__.

Why does assigning a name to a function automatically execute the function? [duplicate]

This question already has answers here:
What is the difference between calling function with parentheses and without in python? [duplicate]
(5 answers)
Closed 3 years ago.
def myfunc():
print("hello")
b=myfunc()
In the above code the output is "hello" just by assigning b to myfunc(). Why is this? I never asked for myfunc() to be executed, I just assigned name to it. I know classes are executed on import, but this isn't a class.
myfunc and myfunc() are not the same thing. In your code, myfunc is a function reference while myfunc() returns the results from calling myfunc.
You want this instead:
b=myfunc
myfunc() means you are making call to the function, since function is not returning b is not getting any value.
if you print b is showing nothing.
if you assign b=myfunc in this case you are passing the reference of function to variable b if you use b() it will execute function body it means b and myfunc will point to same reference.
As there is a difference between print a value or returning something from the function. You are just printing in the function and not returning any value from the function. So if the function is not returning anything, that can't be assigned to the variable... executing the function with myfunc() will only print the value to the terminal.. In case you want to store the value to a variable, you need to return it from the function. :)
def myfunc():
print("Helloo")
b = myfunc()
--> hellloo
b = myfunc
b
--> <function __main__.hello()>
b()
--> hellloo
def myfucn():
return("hellloo")
b = hello()
b
--> hellloo'

NoneType occuring when I run my code [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 5 years ago.
Why does this code return None?
def html_list(inputs_list):
print("<ul>")
for html in inputs_list:
html = ("<li>" + html + "</li>")
print(html)
print("</ul>")
bam = ['boom','bust']
print(html_list(bam))
Your function has print calls within it, but does not return anything. If a function completes without returning, it really returns None.
This means that if you call the function inside a print statement, it will run, do the prints within the function, but return None which will then get passed into the print() function - so this is why you get the intended output and then a "None" at the end.
You can also see this through a more simple example:
>>> def f():
... print("inside f")
...
>>> print(f())
inside f
None

What does <function at ...> mean [duplicate]

This question already has answers here:
What does it mean when the parentheses are omitted from a function or method call?
(6 answers)
Closed 6 months ago.
Here's the code:
def my_func(f, arg):
return f(arg)
print((lambda x: 2*x*x, (5)))
>>>(<function <lambda> at 0x10207b9d8>, 5)
How to solve the error, and can some please explain in a clear language what exactly that error means.
There is no error; you simply supplied two arguments to print, the lambda x: 2*x*x and 5. You're not calling your anonymous function rather, just passing it to print.
print will then call the objects __str__ method which returns what you see:
>>> str(lambda x: 2*x*x) # similarly for '5'
'<function <lambda> at 0x7fd4ec5f0048>'
Instead, fix your parenthesis to actually call the lambda with the 5 passed as the value for x:
print((lambda x: 2*x*x)(5))
which prints out 50.
What's the general meaning of <function at 0x ...>?
That's simply the way Python has chosen to represent function objects when printed. Their str takes the name of the function and the hex of the id of the function and prints it out. E.g:
def foo(): pass
print(foo) # <function foo at 0x7fd4ec5dfe18>
Is created by returning the string:
"<function {0} at {1}>".format(foo.__name__, hex(id(foo)))

Categories

Resources