mirror of
https://github.com/sahinakkaya/til.git
synced 2024-11-24 17:49:36 +01:00
TIL: Defining method outside of class
This commit is contained in:
parent
c22fc567ed
commit
2bbc40bfe1
20
python/defining-method-outside-of-class.md
Normal file
20
python/defining-method-outside-of-class.md
Normal file
@ -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`
|
||||
```
|
Loading…
Reference in New Issue
Block a user