What is the difference between these two examples

Viewed 45

I'm pretty beginner at coding and have coded a few simple games, but just now i have started to learn classes. I'm not sure what's the difference between

user.walk()

and

Person.walk(user)

Here is the class definition:

class Person():
def __init__(self, age, weight, height, first_name, last_name):
    self.age = age
    self.weight = weight
    self.height = height
    self.first_name = first_name
    self.last_name = last_name
def walk(self):
    print('Walking')

Here i define who is user:

user = Person(13, 50, 170, 'First name', 'Last name')

So if anybody has time to answer this question, please help me understand this.

1 Answers

There is basically no difference. user.walk() will end up translating to, effectively, Person.walk(user) but is more readable to the average programmer, not to mention idiomatic.

Specifically, what happens if this. Person.walk(user) is just an ordinary function call on an ordinary function. No magic here. But when Python sees

user.walk()

and there's no walk on the user object (since it's not defined as an instance variable on the object itself), then Python will look on the class. Specifically, it will convert user.walk() into

type(user).walk.__get__(user, type(user))()

And function objects in Python have a __get__ method which converts them to bound method objects, so this effectively becomes

(lambda: Person.walk(user))()

which is, by eta conversion,

Person.walk(user)

Python does all of this behind the scenes, so you don't have to worry about it unless you're doing some advanced metaprogramming.

Related