本篇笔记学习自: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
在上面的类中,我们需要先调用set_balance(设置账户金额)再调用其他的方法(存取金额),这种情况叫做对象没有被完全初始化,我们应该将要初始化的所有遍历都放在init,这样才不会出现一些因为调用顺序出现的麻烦。
- 静态方法:
对象中的方法调用的时候需要对象实例作为参数,静态方法则不用。
class Car(object):
...
@staticmethod
def make_car_sound():
print 'VRooooommmm!'
- 类方法
class Vehicle(object):
...
@classmethod
def is_motorcycle(cls):
return cls.wheels == 2
......