Skip to content

Instantly share code, notes, and snippets.

@yarosla
Created May 17, 2016 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yarosla/a854f72ea9d27e19fde50470af448ac1 to your computer and use it in GitHub Desktop.
Save yarosla/a854f72ea9d27e19fde50470af448ac1 to your computer and use it in GitHub Desktop.
Class methods in Python
import pytest
class A(object):
F='FA'
f1 = lambda: 'f1'
f2 = lambda self: 'f2'
def f3(self):
return 'f3'
f4 = staticmethod(lambda: 'f4')
f5 = classmethod(lambda cls: 'f5')
@staticmethod
def f6():
return 'f6'
@classmethod
def f7(cls):
return 'f7/'+cls.F
class B(A):
F='FB'
def test_f1():
with pytest.raises(TypeError) as exc:
A.f1()
assert exc.value.message == 'unbound method <lambda>() must be called with A instance as first argument (got nothing instead)'
with pytest.raises(TypeError) as exc:
A().f1()
assert exc.value.message == '<lambda>() takes no arguments (1 given)'
def test_f2():
with pytest.raises(TypeError) as exc:
A.f2()
assert exc.value.message == 'unbound method <lambda>() must be called with A instance as first argument (got nothing instead)'
assert A.f2(A()) == 'f2'
assert A().f2() == 'f2'
def test_f3():
with pytest.raises(TypeError) as exc:
A.f3()
assert exc.value.message == 'unbound method f3() must be called with A instance as first argument (got nothing instead)'
assert A.f3(A()) == 'f3'
assert A().f3() == 'f3'
def test_f4():
assert A.f4() == 'f4'
assert A().f4() == 'f4'
def test_f5():
assert A.f5() == 'f5'
assert A().f5() == 'f5'
def test_f6():
assert A.f6() == 'f6'
assert A().f6() == 'f6'
def test_f7():
assert A.f7() == 'f7/FA'
assert A().f7() == 'f7/FA'
def test_B():
assert B.f2(B()) == 'f2'
assert B().f2() == 'f2'
assert B.f3(B()) == 'f3'
assert B().f3() == 'f3'
assert B.f4() == 'f4'
assert B().f4() == 'f4'
assert B.f5() == 'f5'
assert B().f5() == 'f5'
assert B.f6() == 'f6'
assert B().f6() == 'f6'
assert B.f7() == 'f7/FB'
assert B().f7() == 'f7/FB'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment