From 2bbc40bfe1b91269dc2bf17902d911843ca93e56 Mon Sep 17 00:00:00 2001 From: Asocia Date: Tue, 4 May 2021 14:10:09 +0300 Subject: [PATCH] TIL: Defining method outside of class --- python/defining-method-outside-of-class.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 python/defining-method-outside-of-class.md diff --git a/python/defining-method-outside-of-class.md b/python/defining-method-outside-of-class.md new file mode 100644 index 0000000..2b04082 --- /dev/null +++ b/python/defining-method-outside-of-class.md @@ -0,0 +1,20 @@ +You can define methods outside of class definition. However, you need to make sure that you bound the method *to the class* itself **not** instance. + +```python +class Foo: + x = 42 + + +def bar(self): + return self.x + + +if __name__ == "__main__": + foo = Foo() + + Foo.bar = bar + print(foo.bar()) # 42 + + foo.bar = bar + print(foo.bar()) # error, because `bar` doesn't know about `self` +```