本篇筆記學習自:Improve Your Python: Python Classes and Object Oriented Programming
what is a class? Simply a logical grouping of data and functions (the latter of which are frequently referred to as "methods" when defined within a class).
Classes can be thought of as blueprints for creating objects.
So what's with that self parameter to all of the Customer methods? What is it? Why, it's the instance, of course!
jeff.withdraw(100.0) is just shorthand for Customer.withdraw(jeff, 100.0), which is perfectly valid (if not often seen) code.
- init
class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have the
following properties:
Attributes:
name: A string representing the customer's name.
balance: A float tracking the current balance of the customer's account.
"""
def __init__(self, name):
"""Return a Customer object whose name is *name*."""
self.name = name
def set_balance(self, balance=0.0):
"""Set the customer's starting balance."""
self.balance = balance
def withdraw(self, amount):
"""Return the balance remaining after withdrawing *amount*
dollars."""
if amount > self.balance:
raise RuntimeError('Amount greater than available balance.')
self.balance -= amount
return self.balance
def deposit(self, amount):
"""Return the balance remaining after depositing *amount*
dollars."""
self.balance += amount
return self.balance
在上面的類中锰扶,我們需要先調(diào)用set_balance(設置賬戶金額)再調(diào)用其他的方法(存取金額),這種情況叫做對象沒有被完全初始化,我們應該將要初始化的所有遍歷都放在init,這樣才不會出現(xiàn)一些因為調(diào)用順序出現(xiàn)的麻煩肖卧。
- 靜態(tài)方法:
對象中的方法調(diào)用的時候需要對象實例作為參數(shù),靜態(tài)方法則不用嚼隘。
class Car(object):
...
@staticmethod
def make_car_sound():
print 'VRooooommmm!'
- 類方法
class Vehicle(object):
...
@classmethod
def is_motorcycle(cls):
return cls.wheels == 2
......