python学习笔记之类

和其他面向对象的编程语言一样,python也是可以定义类的,下面我将对python中的类做一下总结,主要包括:类的定义、继承、静态方法、类方法、特性和运算符重载。

1.类的定义

和c++一样,Python使用关键字class定义类。

 

  1. class People(object):
  2. numbers = 0
  3. def __init__(self, name, age, male, address):
  4. self.name = name
  5. self.age = age
  6. self.male = male
  7. self.address = address
  8. People.numbers += 1
  9. def __del__(self):
  10. People.numbers -= 1
  11. def eat(self, food):
  12. print self.name + ' is eating ' + food + '.'
  13. >>> wuyuan = People('wuyuan', 20, True, 'wuyuans.com')
  14. >>> wuyuan.eat('apple')
  15. wuyuan is eating apple.
  16. >>> wuyuan.name
  17. 'wuyuan'

类通常由类变量、方法和属性组成,其中类变量相当于c++中类的静态变量,所有该类的实例都可以访问,通常用于保存公共资源和类实例的相关信息,比如实例的数量。Python中类的方法和一般的有点不一样,多了个self,这个相当于c#中的this变量,表示当前对象实例,在类中访问实例方法和属性时都需要使用self来指示。属性就是类的实例变量,也可以说是成员变量,一般在构造函数init中定义,del为类的析构函数。

2.类的继承

在class语句中可以使用以逗号分隔的基类列表来指定继承,如果未指明将默认继承object类。

 

  1. class Student(People):
  2. def __init__(self, name, age, male, address, school):
  3. self.school = school
  4. super(Student, self).__init__(name, age, male, address)
  5. def eat(self, food):
  6. print 'Student ' + self.name + ' is eating ' + food + '.'
  7. >>> wuyuan.eat('apple')
  8. Student wuyuan is eating apple.

子类可以重定义父类的方法,比如构造函数init,以此来添加子类成员变量。使用super函数也可以在构造函数中调用父类的init,或者直接使用People.init()调用。在使用super时父类在定义时必须继承object类,否则出现TypeError: TypeError: must be type, not classobj

3.静态方法和类方法

Python中类的方法一般以实例作为第一个参数self传递,但也有例外的情况,比如静态方法和类方法。

3.1.静态方法

和其他面向对象语言一样,Python的类中也可以定义静态方法,使用@staticmenthod装饰器定义。因为没有传递self参数,静态方法不会对任何实例类型进行操作。

 

  1. class Foo(object):
  2. @staticmethod
  3. def add(x, y):
  4. return x + y
  5. >>> Foo.add(1, 2)
  6. 3

如果在编写类时需要采用不同的方式创建新实例,比如工厂模式,则通常使用静态方法。

3.2.类方法

类方法和静态方法很相似,不同的是当前类将作为第一个参数cls传递,使用@classmethod装饰器定义。

 

  1. class Times(object):
  2. factor = 1
  3. @classmethod
  4. def mul(cls, x):
  5. return cls.factor * x
  6. class TwoTimes(Times):
  7. factor = 2
  8. >>> Times.mul(3)
  9. 3
  10. >>> TwoTimes.mul(3)
  11. 6

TwoTimes是Times的子类,但在调用mul时cls为TwoTimes,所以cls.factor为2。

4.特性

特性是一种特殊的属性,访问它时会计算他的值,和c#中的属性类似,使用@property装饰器定义。

 

  1. class Circle(object):
  2. def __init__(self, r):
  3. self.__radius = r
  4. @property
  5. def area(self):
  6. return math.pi * self.__radius ** 2
  7. @property
  8. def perimeter(self):
  9. return 2 * math.pi * self.__radius
  10. @property
  11. def radius(self):
  12. return self.__radius
  13. @radius.setter
  14. def radius(self, value):
  15. if not isinstance(value, float):
  16. raise TypeError('Must be a float')
  17. self.__radius = value
  18. @radius.deleter
  19. def radius(self):
  20. self.__radius = 0
  21. >>> c = Circle(3.0)
  22. >>> c.radius
  23. 3.0
  24. >>> c.area
  25. 28.274333882308138
  26. >>> c.perimeter
  27. 18.84955592153876
  28. # 赋值
  29. >>> c.radius = 4.0
  30. >>> c.radius
  31. 4.0
  32. # 删除
  33. >>> del c.radius
  34. >>> c.radius
  35. 0

当定义了特性后,只能简单访问该特性,要做赋值和删除操作的话必须附加setter和deleter方法。

5.运算符重载

和c++一样,Python也可以对运算符进行重载。可以重载的方法如下表所示。

MethodOverloadsCall for
init 构造函数 X=Class()
del 析构函数 对象销毁
repr 打印转换 print X,repr(X)
str 打印转换 print X,str(X)
call 调用函数 X()
getattr 限制 X.undefine
setattr 取值 X.any=value
getitem 索引 X[key],For If
setitem 索引 X[key]=value
len 长度 len(X)
iter 迭代

For In

add + X+Y,X+=Y
sub - X-Y,X-=Y
mul * X*Y
radd 右加+ +X
iadd += X+=Y
or | X|Y,X|=Y
cmp 比较 == X==Y,X<y< td="">
lt 小于< X<y< td="">
eq 等于= X=Y

 

  1. class Number(object):
  2. def __init__(self, value):
  3. self.value = value
  4. # 加重载
  5. def __add__(self, other):
  6. return Number(self.value + other.value)
  7. # 打印重载
  8. def __str__(self):
  9. return 'The value is %d.' % self.value
  10. # 比较重载
  11. def __cmp__(self, other):
  12. return cmp(self.value, other.value)
  13. >>> x = Number(1)
  14. >>> y = Number(2)
  15. >>> print x + y
  16. The value is 3.
  17. >>> x > y
  18. False
  19. >>> x < y
  20. True
posted @ 2017-07-28 18:45  天涯海角路  阅读(94)  评论(0)    收藏  举报