#๐Ÿ”’ Difference between f=int and def g(x): return int(x)?

20 messages ยท Page 1 of 1 (latest)

mighty marlin
#

How is f different from g? Exactly, Demo.f works but Demo.g does not. I am pretty sure both get the self parameter, but what happens to it in the f case? (I have more tests but they show the same result.)

f = int
def g(x):
    return int(x)

class Demo():
    def this_works(self, n):
        return int(n)

    def not_this(self, m):
        return int(self, m)

Demo.this_also = Demo.this_works
Demo.surprisingly = int

Demo.f = f
Demo.g = g

d = Demo()

n=0
for af in [d.this_works, d.this_also, d.not_this, d.f, d.g]:
    n += 1
    print(f'Test #{n} of {str(af)}')
    try:
        print(af(str(n)))
    except TypeError as e:
        print(f'Failed with {e}')
thin hatchBOT
#

@mighty marlin

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

tidal prairie
#

int is a callable class/type
g is a function

#

lemme test it myself

#

int is a class. so when you assign it to demo type. it is set as an attribute, like a typeObject

g is a function. so when you assign it to demo type. it is set as an method and methods take an instance of self. which your function does not. hence it throws the error

coarse needle
#

g behaves as expected. doing Demo.g = g is basically the same as defining g in your class.

mighty marlin
#

that sounds like part of it... so what happens to the self parameter in f? does the callable class not get it?

tidal prairie
coarse needle
#

int is a type.. meaning it got an __init__ and that one has a self defined

tidal prairie
#

oh, so you are essentially initializing Demo class as an int

mighty marlin
#

in case it wasn't clear - I saw this code as part of the Lark parser and did not understand why int worked when it looked different from my this_works function

coarse needle
#

!e

class myint:
    def __init__(self, val):
        self.val = val

class Demo:
    ...

Demo.f = myint

d = Demo()
d.f(123)
thin hatchBOT
#

@coarse needle :warning: Your 3.12 eval job has completed with return code 0.

[No output]
coarse needle
#

int works for the same reason myint works, I'd assume.

#

it's a class/type.. not a function

#

it's not getting converted to a bound method

mighty marlin
#

!close

thin hatchBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.