什么是class?简单来说,class是数据和函数有逻辑的组合。所谓逻辑的组合指的是数据和class里的函数都是息息相关的。所以class “can be thought of as blueprints for creating objects”。 这里我举一个简单的例子:
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, balance=0.0):
"""Return a Customer object whose name is *name* and starting balance is *balance*."""
self.name = name
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
所以我们可以看到,class里面重要的两个元素: Attributes and Methods。因为我们需要理清楚这两者之间的关系。Attribute就是这个属于这个class 的对象的属性。比如这个例子里的名字(name)和余额(balance)。基于这些属性的对象,我们定义了方法取钱(withdraw)和存钱(deposit)。所以整个class就显得非常清晰了。
除此之外,当class复杂起来的时候,我们还需要考虑比如哪些methods是static的;以及有没有必要建立abstract base class让我们去inherit。