如何设计一个类python_如何设计好一个python的类

什么是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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值