Created
October 25, 2018 00:53
-
-
Save msullivan/dddcf35fddd83ad3a6a31da18c338278 to your computer and use it in GitHub Desktop.
python static methods that can't be called on objects
This file contains hidden or 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
from types import MethodType | |
class strict_staticmethod: | |
def __init__(self, f): | |
self.f = f | |
def __get__(self, obj, type=None): | |
if obj is not None: | |
raise AttributeError("strict_staticmethod can't be accessed through obj") | |
return self.f | |
class strict_classmethod: | |
def __init__(self, f): | |
self.f = f | |
def __get__(self, obj, type=None): | |
if obj is not None: | |
raise AttributeError("strict_classmethod can't be accessed through obj") | |
if type is None: | |
raise TypeError | |
return MethodType(self.f, type) | |
# Test | |
class A: | |
@strict_staticmethod | |
def foo(x): | |
print('foo:', x) | |
@strict_classmethod | |
def bar(cls, x): | |
print('bar:', cls.__name__, x) | |
class B(A): pass | |
A.foo(5) | |
# A().foo(5) # fails | |
A.bar(5) | |
# A().bar(5) # fails | |
B.bar(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(because a friend asked about it)