Files
freeCodeCamp/guide/english/python/object-oriented-programming/methods/index.md

38 lines
991 B
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
title: Methods
---
## Methods
In object oriented programming a function within a class or an object is named a method. Imagine you have a cat object and inside the class there is a funcion named scratch, you can now use the cat's scratch method by calling it in the following way:
```py
cat.scratch(somePerson)
```
## Different kind of methods
2018-10-12 15:37:13 -04:00
There are different types of methods you can define in a class, some of them are listed here.
2018-10-12 15:37:13 -04:00
The constructor, a method that is executed when the object is created:
2018-10-12 15:37:13 -04:00
```py
class Cat:
def __init__(self, name): // Constructor which recieves a name
self.name = name
```
2018-10-12 15:37:13 -04:00
Standard methods:
```py
class Cat:
name = "Bob"
def scratch(self, person): // Standard method, recieves person to scratch
print(self.name + " scratched " + person)
```
2018-10-12 15:37:13 -04:00
The destructor, a method that is executed when the object is deleted by the garbage collector.
```py
class Cat:
name = "Bob"
def __del__(self):
print(name + " is no more.")
```