ChimeraCoder / go-for-pythonists

Presentation given at New York Python Meetup

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Explain how any type can have methods, not just structs

ChimeraCoder opened this issue · comments

Maps, slice, functions, etc. Via @sethwklein again. This would be useful for a longer presentation.

Also, note that methods must be defined in the same package as the type.

While a longer presentation could be neat, I'm just thinking a simple s/struct/type/ on these two lines:
"If a struct provides the methods of an interface, it belongs to the interface"
and
"Like Python, you simply use struct and it 'just works'."
People will still think it's structs only, but at least then you technically won't have mentioned only structs.

Agreed, that's the simplest fix for now. It would be more complicated to explain this in detail - while Python technically allows this behavior, I think even some relatively experienced Pythonists wouldn't be familiar with the proper way to add a method to a function:

import types

def foo(x):
    return 2*x


foo.attribute = 23


#without types.MethodType, we'd be assigning an unbound function
#whereas methods are bound functions
foo.myMethod = types.MethodType(lambda x, y: 3*x(y), foo) 

print(foo(6))
print(foo.attribute)
print(foo.myMethod(6))

Which will print

12
23
36

...which, I admit, I looked up myself!