Last active
August 29, 2015 13:57
-
-
Save icecrime/9705220 to your computer and use it in GitHub Desktop.
Go interfaces and type assertions compared to Python's Abstract Base Classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import abc | |
### Go equivalent | |
# | |
# type Lock interface { | |
# Lock() | |
# Unlock() | |
# } | |
class Lock: | |
__metaclass__ = abc.ABCMeta | |
@abc.abstractmethod | |
def Lock(): | |
pass | |
@abc.abstractmethod | |
def Unlock(): | |
pass | |
### Go equivalent | |
# | |
# type Mutex struct {} | |
# | |
# func (m Mutex) Lock() {} | |
# func (m Mutex) Unlock() {} | |
class Mutex(object): | |
def Lock(): | |
pass | |
def Unlock(): | |
pass | |
# /!\ This is the important difference /!\ | |
# Pyhon's abc requires explicit type registration. | |
Lock.register(Mutex) | |
### Go equivalent | |
# | |
# func main() { | |
# var m Mutex | |
# var o interface{} = m | |
# | |
# res, ok := o.(Lock) | |
# fmt.Println(res, ok) | |
# } | |
def type_assertion(instance, type_): | |
return instance if isinstance(instance, type_) else None | |
if __name__ == "__main__": | |
m = Mutex() | |
print type_assertion(m, Lock) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment