class,object,method这些概念对于小白还是有点抽象,本篇以实例为主,第二个例子和代码都来自于MIT的公开课。《Introduction to Computer Science and Programming in Python》。
简单例子
一个常见的类,list。
x_list = ['Peggy','Susie','Daniel']
list是一个类(class),x_list是对象(object),也可以说是类的一个实例(instance)。在list这个类里面,定义了 +, *, append(),pop() 等等方法(method)。
编写一个类
任务:编写一个类,Fraction。
要求:
1. 输入是分子和分母,都是整型。
2. 可以做分数加减法和倒数运算。
3. 输出有分数形式和小数形式。
步骤:
1. 写开头
class Fraction(object):
2.__init__()方法,接受输入参数,赋值给class的类型。赋值之前先判断输入是否为整型。
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(c)) 和 print(Fraction.__float__(c))。这类方法是python预先保留的。
另一类是inverse(),格式只能为object.method()。这种方式强调了inverse()是属于Fraction 类的一个method。这类方法是用户定义的。
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)