python类与对象编程_Python类和面向对象编程

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

......

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值