-
-
Save davidbgk/384884 to your computer and use it in GitHub Desktop.
when you want to use both a classmethod and the function with a class instance
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
# classinstancemethod, when you want to use both a classmethod and the function with a class instance | |
## Descriptors | |
## Anything with __get__ and optionally __set__: | |
class classinstancemethod(object): | |
def __init__(self, func): | |
self.func = func | |
def __get__(self, obj, type=None): | |
def repl(*args, **kw): | |
return self.func(obj, type, *args, **kw) | |
return repl | |
## Then to use it: | |
class MyValidator(object): | |
date_format = '%Y-%m-%d' | |
def __init__(self, date_format=None): | |
if date_format is not None: | |
self.date_format = date_format | |
@classinstancemethod | |
def check_input(self, cls, input): | |
if self is None: | |
self = cls() | |
return time.strptime(input, self.date_format) | |
MyValidator('%m-%d-%Y').check_input('5-1-2010') | |
MyValidator.check_input('2010-05-01') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment