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

本文介绍了面向对象编程中的类和对象概念,包括类作为数据和方法的逻辑分组,以及实例(对象)的使用。通过示例展示了`__init__`方法在初始化对象时的重要性,强调了正确初始化所有属性以避免后续操作出现问题。同时提到了静态方法和类方法的区别,静态方法不需要实例对象作为参数,而类方法可以访问类的属性。
摘要由CSDN通过智能技术生成

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

......

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值