> For the complete documentation index, see [llms.txt](https://lamsaodecode.gitbook.io/python-reference/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lamsaodecode.gitbook.io/python-reference/class.md).

# Class

Lập trình hướng đối tượng là một khái niệm không thể thiếu trong hầu hết các ngôn ngữ thông dụng hiện nay. Python cũng hỗ trợ lập trình hướng đối tượng với các khái niệm Class, Object, Override...

## Khai báo một Class

#### Cú pháp:

```python
class myclass([parentclass]):
    assignments
    def __init__(self):
        statements
    def method():
        statements
    def method2():
        statements
```

#### Ví dụ:

```python
class animal():
    name = ''
    age = 0
    def __init__(self, name = '', age = 0):
        self.name = name
        self.age = age
        
    def show(self):
        print 'My name is ', self.name
        
    def run(self):
        print 'Animal is running...'
        
    def go(self):
        print 'Animal is going...'
    
    class dog(animal):
    def run(self):
        print 'Dog is running...'
    
myanimal = animal()
myanimal.show()
myanimal.run()
myanimal.go()
    
mydog = dog('Fairy')
mydog.show()
mydog.run()
mydog.go()
```

#### Kết quả:

```python
My Name is
Animal is running...
Animal is going...
My Name is Lucy
Dog is running...
Animal is going...
```

Trong ví dụ trên thì:

* `animal` và `dog` là 2 class. Trong đó class dog kế thừa từ class cha là `animal` nên sẽ có các phương thức của class `animal`.
* `name` và `age` là thuộc tính (Attribute) của class.
* Phương thức `init(self)` là hàm tạo của class. Hàm này sẽ được gọi mỗi khi có một object mới được tạo (từ một class), gọi là quá trình tạo `instance`.
* `show()` , `run()` và `go()` là 2 phương thức của 2 class. Khi khai báo phương thức có kèm tham số `self` dùng để truy cập ngược lại object đang gọi. Lúc gọi phương thức thì không cần truyền tham số này.
* Phương thức `run()` của class dog gọi là `override` của phương thức `run()` của class `animal`.

## Follower me

* **Facebook**: [https://www.facebook.com/lamsaodecode](https://www.facebook.com/100013678592616)
* **Blog:** <https://lamsaodecode.blogspot.com>
* **Github:** <https://lamsaodecode.github.io/introduction>
