1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
|
__doc__ = u"""
>>> class1.plus1(1)
2
>>> class2.plus1(1)
2
>>> class3.plus1(1)
2
>>> class4.plus1(1)
2
>>> class4().plus1(1)
2
>>> class4.bplus1(1)
2
>>> class4().bplus1(1)
2
"""
cimport cython
def f_plus(a):
return a + 1
class class1:
plus1 = f_plus
class class2(object):
plus1 = f_plus
cdef class class3:
plus1 = f_plus
class class4:
@staticmethod
def plus1(a):
return a + 1
@staticmethod
@cython.binding(True)
def bplus1(a):
return a + 1
def nested_class():
"""
>>> cls = nested_class()
>>> cls.plus1(1)
2
>>> obj = cls()
>>> obj.plus1(1)
2
"""
class class5(object):
def __new__(cls): # implicit staticmethod
return object.__new__(cls)
@staticmethod
def plus1(a):
return a + 1
return class5
cdef class BaseClass(object):
"""
Test cdef static methods with super() and Python subclasses
>>> obj = BaseClass()
>>> obj.mystaticmethod(obj, 1)
1
>>> BaseClass.mystaticmethod(obj, 1)
1
>>> obj.mystaticmethod2(1, 2, 3)
1 2 3
>>> BaseClass.mystaticmethod2(1, 2, 3)
1 2 3
"""
@staticmethod
def mystaticmethod(self, arg1):
print arg1
@staticmethod
@cython.binding(True)
def mystaticmethod2(a, b, c):
print a, b, c
cdef class SubClass(BaseClass):
"""
>>> obj = SubClass()
>>> obj.mystaticmethod(obj, 1)
1
2
>>> SubClass.mystaticmethod(obj, 1)
1
2
"""
@staticmethod
def mystaticmethod(self, arg1):
print arg1
super().mystaticmethod(self, arg1 + 1)
class SubSubClass(SubClass):
"""
>>> obj = SubSubClass()
>>> obj.mystaticmethod(obj, 1)
1
2
3
>>> SubSubClass.mystaticmethod(obj, 1)
1
2
3
"""
@staticmethod
def mystaticmethod(self, arg1):
print arg1
super().mystaticmethod(self, arg1 + 1)
cdef class ArgsKwargs(object):
@staticmethod
def with_first_arg(arg1, *args, **kwargs):
"""
>>> ArgsKwargs().with_first_arg(1, 2, 3, a=4, b=5)
(1, 'pos', 2, 3, ('a', 4), ('b', 5))
"""
return (arg1, 'pos') + args + tuple(sorted(kwargs.items()))
@staticmethod
def only_args_kwargs(*args, **kwargs):
"""
>>> ArgsKwargs().only_args_kwargs()
()
>>> ArgsKwargs().only_args_kwargs(1, 2, a=3)
(1, 2, ('a', 3))
"""
return args + tuple(sorted(kwargs.items()))
@staticmethod
def no_args():
"""
>>> ArgsKwargs().no_args()
OK!
"""
print("OK!")
class StaticmethodSubclass(staticmethod):
"""
>>> s = StaticmethodSubclass(None)
>>> s.is_subtype()
True
"""
def is_subtype(self):
return isinstance(self, staticmethod)
|