📃
Python Reference
  • Installation
  • First Steps
  • Variables
  • Operators and Expressions
  • Control Flow
  • Loops
  • Functions
  • String
  • List
  • Dictionany
  • Modules
  • Class
  • File
  • Folder
  • Module os
  • Image
  • JSON
  • XML
  • Connection MySQL
  • Connection Redis
  • Connection Memcached
  • Connection RabbitMQ
  • Restful client
  • STMP
  • Socket
Powered by GitBook
On this page
  • Khai báo một Class
  • Follower me

Was this helpful?

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:

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

Ví dụ:

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ả:

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

PreviousModulesNextFile

Last updated 4 years ago

Was this helpful?

Facebook:

Blog:

Github:

https://www.facebook.com/lamsaodecode
https://lamsaodecode.blogspot.com
https://lamsaodecode.github.io/introduction