本节课主要讲述了class,object,method这些概念。
1.首先讲述了python中的任何一个数据类型都是一个类。任何一个数据,都是类的一个实体。类的作用能够更好地抽象所描述的对象,将相关的数据和方法封装起来。对于相似功能的方法,因为属于不同的类,可以有同样的命名,但是功能却更适合所属的类。
2.其次举例说明了类,对象,方法的定义,实现和使用的方法。这里举了一个Fraction类的编写过程的例子。
本篇笔记和代码都来自于MIT的公开课,第八课,面向对象编程。《Introduction to Computer Science and Programming in Python》。
什么是对象
Python中的每一种数据类型都是一个对象,比如int,float,string,list,dict。都是一个对象。每个对象都有
- 一种类型
- 一种数据表示方法
- 一些方法,用于交互
简单例子
一个常见的类,list。
x_list = ['Peggy','Susie','Daniel']
list是一个类(class),x_list是对象(object),也可以说是类的一个实例(instance)。在list这个类里面,定义了 +, *, append(),pop() 等等方法(method)。
编写一个类
任务:编写一个类,Fraction。
要求:
- 输入是分子和分母,都是整型。
- 可以做分数加减法和倒数运算。
- 输出有分数形式和小数形式。
步骤:
1.写class的定义,定义的格式如下
class 关键字 class的名称 (class的父类)
class Fraction(object):
object意味着Fraction是一个python对象,并且继承了object的所有attribute。
object是Fraction的一个超集,而Fraction是object的一个子集。
2._init_()方法,接受输入参数,赋值给class的类型。赋值之前先判断输入是否为整型。所有在该类型下使用的instance variable,都必须在__init__()方法类定义,最好不要在其他方法内随意写self.variable,以免在继承时发生错误。初始化时将没有传入参数的变量设置为默认值或者为空。
def __init__(self, num, denom):
""" num and denom are integers """
assert type(num) == int and type(denom) == int, "ints not used"
self.num = num
self.denom = denom
3._str_()方法,用来定义使用print(object)的输出格式。如果没有定义,则打印结果会是 xx object at xx address。
def __str__(self):
""" Retunrs a string representation of self """
return str(self.num) + "/" + str(self.denom)
4._add_(),_sub_(),和_float_()方法,分别对应操作符 +,- 和float()方法。
def __add__(self, other):
""" Returns a new fraction representing the addition """
top = self.num*other.denom + self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
5.inverse()方法,用来求倒数。
def inverse(self):
""" Returns a new fraction representing 1/self """
return Fraction(self.denom, self.num)
编写完成,就可以定义Fraction的对象,然后完成相应的操作和运算。
方法有两类,一类是像 _init_(),前后各有两个下划线的,他们对应特定的操作符。这种方法使用时可以直接使用method(object),也可以class.methed(object).比如下方例子print(float©) 和 print(Fraction._float_©)。这类方法是python预先保留的。
另一类是inverse(),格式只能为object.method()。这种方式强调了inverse()是属于Fraction 类的一个method。这类方法是用户定义的。在类的定义过程中,一个成员方法可以直接引用类的其他成员方法,引用方法为 class.method(self, variables),记住一定要写self。
以上代码的运行结果如下
a = Fraction(1,4)
b = Fraction(3,4)
c = a + b # c is a Fraction object
print(c)
print(float(c))
print(Fraction.__float__(c))
print(float(b.inverse()))
##c = Fraction(3.14, 2.7) # assertion error
##print a*b # error, did not define how to multiply two Fraction objects
16/16
1.0
1.0
1.3333333333333333
以下是一些简单的出错信息解释。
c = Fraction(3.14, 2.7)
#assertion error,__init__()要求输入必须是整型。
print a*b
#error, did not define how to multiply two Fraction objects,没有定义两个Fraction object如何相乘
len(a)
#object of type 'Fraction' has no len()。Fraction类中没有定义len()。
完整代码如下,版权归MIT 公开课MIT的公开课《Introduction to Computer Science and Programming in Python》所有。
#################
## EXAMPLE: simple class to represent fractions
## Try adding more built-in operations like multiply, divide
### Try adding a reduce method to reduce the fraction (use gcd)
#################
class Fraction(object):
"""
A number represented as a fraction
"""
def __init__(self, num, denom):
""" num and denom are integers """
assert type(num) == int and type(denom) == int, "ints not used"
self.num = num
self.denom = denom
def __str__(self):
""" Retunrs a string representation of self """
return str(self.num) + "/" + str(self.denom)
def __add__(self, other):
""" Returns a new fraction representing the addition """
top = self.num*other.denom + self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __sub__(self, other):
""" Returns a new fraction representing the subtraction """
top = self.num*other.denom - self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __float__(self):
""" Returns a float value of the fraction """
return self.num/self.denom
def inverse(self):
""" Returns a new fraction representing 1/self """
return Fraction(self.denom, self.num)