快速理解物件導向程式設計

翻譯不完整。請協助 翻譯此英文文件

導論

這個教程會透過範例碼與簡單而實際的解釋,說明如何入門物件導向程式設計(object-oriented programming)。

這個教程是針對這樣的你:

  • 你已經知道如何在其他語言使用類別(class)與物件(object)而你只是想知道如何在 Python 裡實做。
  • 你不懂如何使用物件,而你想用簡單、並省去大篇幅的理論下理解。

這個教程不是針對這樣的你:

  • 你對進階的 Python 程式設計有興趣,想對 Python 的內部工作機制有深切的理解。

如果你知道何謂物件,你可以略過導論

何謂物件?

創建物件就像是創造你自己的變數型別(variable type)。

這個物件可以包含好幾個變數(稱為屬性,attributes/properties),裡面儲存不同型別的資料。這個物件也可以包含已經自己設定好的函式(稱為 methods),用於操作物件的屬性。

你可以用同一個型別去創建很多個物件(同一個類別),每個物件都有屬於自己的數值。

如果你要為銀行設計一個程式,你要為用戶的帳戶創建一個物件。每個新用戶都會有包含各自資訊的物件。

範例:

object_Account1 = BankAccount()    # 創建兩個新物件
object_Account2 = BankAccount()    # newAccount 是你所創建的 type 名

print object_Account1.userName    # Prints the name of the account
print object_Account1.balance    # Prints the account balance

print object_Account2.userName    # Prints a different name
print object_Account2.balance    # Prints a different balance

這兩個物件都屬於同一個類別,所以這些變數有同一個變數(also called properties or attributes)但有著不同的數值。

物件也各自能擁有在屬性上操作的函式(又稱作方法,method)。

print object_Account1.withdrawMoney(100)
print object_Account2.depositMoney(300)

An object's attributes and methods are defined in its class.

Object Oriented Programming is supposed to be the most practical approach for dealing with today's programming situations.

Enough Theory.

So let's get into it right away and start punching some code.

Creating a Class with Methods and Properties:

class BankAccount:
    """ Class for Bank Accounts"""

    type = 'Normal Account'    # variable shared by all objects of the class

    def __init__(self, name):
        # default variables unique to each object:
        self.userName = name
        self.balance = 0.0

    # Object Methods:

    def showBalance(self):
        print self.balance
        return

    def withdrawMoney(self, amount):
        self.balance -= amount
        return

    def depositMoney(self, amount):
        self.balance += amount
        return

The special method __init__() is automatically invoked when a new object is created.
You can pass arguments to it and use it to instantiate objects with customized initial data.

Create an Object from a Class and Use it:

object1 = BankAccount("Im 1")    # create new instance of ClassName
object2 = BankAccount("Me 2")    # create another instance

# access object properties
print object1.userName    #'Im 1'
print object2.userName    #'Me 2'

# access object methods
object1.depositMoney(100)
object2.depositMoney(200)

print object1.balance    # 'Im 1'
print object2.balance    # 'Me 2'
# same as:
object1.showBalance()    # 100
object2.showBalance()    # 200

print object1.type    # 'Normal Account'
print object2.type    # 'Normal Account'

By simply assigning a value, you can also assign a new property to an object accessible only to that object. You can also delete an object property by using 'del':

object1.discount_code = 'secret'

print object1.discount_code    # 'secret'
print object2.discount_code    # Throws Error: AttributeError: object2 instance has no attribute 'discount_code'

del object1.discount_code    # back to how it originally was

 

Quick Theory
 

You will eventually realize that everything in Python is an object. It means that everything in Python has a class. You can find out which class an object belongs to by using the default property __class__:

account3 = BankAccount()
print account3.__class__    # __main__.BankAccount

string = 'Cat'
print string.__class__        # <type 'str'>

So yes, [1,2].reverse() is a method of the native class 'list'.

Inheritance

You can make a new class inherit all the original methods and attributes from another class, but you can still give the new class its own properties to extend its functionality:

class ExecutiveAccount( BankAccount ):
    # Overriden attribute
    type = 'Executive Account'

    # Extended functionality
    def requestCredit(self, amount):
        self.balance += amount

executive = ExecutiveAccount()

When you access an object property, the interpreter looks for it in the object class. If it's not there, the interpreter proceeds all the way up the class inheritance chain until the first occurence is found.

You can call the original property from an overriding class like this:

class SpecialExecutiveAccount( ExecutiveAccount ):
    def requestCredit(self, amount):
        self.balance = ExecutiveAccount.requestCredit(self, amount)
        return

__init__() methods are not inherited

You can use isinstance() to check if an object is an instance or subinstance of a class.
You can use issubclass() to check if one class derives from another:

isinstance(executive, SpecialExecutiveAccount)        # True
isinstance(executive, BankAccount)            # True, derived
issubclass(SpecialExecutiveAccount, BankAccount)    # True

多重繼承

There is support for inherting from multiple classes:

class CustomizedClass( ExecutiveAccount, EnterpriseAccount, InternationalAccount ):
    # . . .


If the interpreter doesn't find a requested attribute in the class, the interpreter proceeds left to right, in Executive and then in Enterprise and so on.

Iterators

You probably know that you can iterate through the elements of a Python object with for loops:

for i in ['a', 'b', 'c']: print i
# 'a'
# 'b'
# 'c'

for i in 'abc': print i # same as above,

You can also use iterators with the function iter():

iterator = iter('abc')
iterator.next() # 'a'
iterator.next() # 'b'
iterator.next() # 'c'

You can add iterating functionality to your objects by defining the special __iter__() method, along with a next() method:

class IterableAccount( BankAccount ):
    def __init__(self, name):
        self.userName = name
        self.index = len(self.userName)

    def __iter__(self):
        return self

    def next(self):
        # iterators will iterate through the userName in reverse order
        if self.index == 0:
            raise StopIteration
        self.index -= 1
        return self.userName[self.index]

iterable = IterableAccount ('stack')
for i in iterable: print i
# 'k'
# 'c'
# 'a'
# 't'
# 's'

 

文件標籤與貢獻者

 此頁面的貢獻者: iigmir
 最近更新: iigmir,