2014-06-08 22:28:44 +03:00
|
|
|
# Calling an inherited classmethod
|
|
|
|
|
class Base:
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def foo(cls):
|
|
|
|
|
print(cls.__name__)
|
|
|
|
|
|
2017-02-15 18:11:16 +03:00
|
|
|
try:
|
|
|
|
|
Base.__name__
|
|
|
|
|
except AttributeError:
|
|
|
|
|
print("SKIP")
|
2017-06-10 20:03:01 +03:00
|
|
|
raise SystemExit
|
2017-02-15 18:11:16 +03:00
|
|
|
|
2014-06-08 22:28:44 +03:00
|
|
|
class Sub(Base):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Sub.foo()
|
2015-12-09 17:30:01 +00:00
|
|
|
|
|
|
|
|
# overriding a member and accessing it via a classmethod
|
|
|
|
|
|
|
|
|
|
class A(object):
|
|
|
|
|
foo = 0
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def bar(cls):
|
|
|
|
|
print(cls.foo)
|
|
|
|
|
|
|
|
|
|
def baz(self):
|
|
|
|
|
print(self.foo)
|
|
|
|
|
|
|
|
|
|
class B(A):
|
|
|
|
|
foo = 1
|
|
|
|
|
|
|
|
|
|
B.bar() # class calling classmethod
|
|
|
|
|
B().bar() # instance calling classmethod
|
|
|
|
|
B().baz() # instance calling normal method
|
2024-07-24 17:17:39 +10:00
|
|
|
|
|
|
|
|
# super inside a classmethod
|
|
|
|
|
# ensure the argument of the super method that is called is the child type
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class C:
|
|
|
|
|
@classmethod
|
|
|
|
|
def f(cls):
|
|
|
|
|
print("C.f", cls.__name__) # cls should be D
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def g(cls):
|
|
|
|
|
print("C.g", cls.__name__) # cls should be D
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class D(C):
|
|
|
|
|
@classmethod
|
|
|
|
|
def f(cls):
|
|
|
|
|
print("D.f", cls.__name__)
|
|
|
|
|
super().f()
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def g(cls):
|
|
|
|
|
print("D.g", cls.__name__)
|
|
|
|
|
super(D, cls).g()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
D.f()
|
|
|
|
|
D.g()
|
|
|
|
|
D().f()
|
|
|
|
|
D().g()
|