python面向对象
面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想。
创建一个学生类及其实例:
class Student(object): def _init_(self,name,sex,age,english,math): self._name = name self._sex = sex self._age = age self._english = english self._math = math def sumScore(self): return self._english + self._math if __name__=='__main__': s = Student() s._name = '小红' s._age = 18 s._sex = '女' s._english = 82 s._math = 78 a = s.sumScore() print a
继承和多态
举例为:狗和猫都是动物
class Animal(object): def run(self): print 'Animal is running...' class Dog(Animal): def run(self): print 'Dog is running...' class Cat(Animal): pass if __name__=='__main__': d = Dog() c = Cat() d.run() c.run()
判断一个变量是否是某个类型可以用isinstance()
判断:
isinstance(d,Dog) isinstance(c,Cat)
开闭原则:
对扩展开放:允许新增Animal子类;
对修改封闭:不需要修改依赖Animal类型的run_twice()
等函数。
def run_kindof(animal): animal.run() a = Animal() d = Dog() c = Cat() run_kindof(a) run_kindof(d) run_kindof(c)
type():获取对象类型(包括基本类型、函数、类)
print type('1') <type 'str'> print type(1) <type 'int'> print type(a) <class '__main__.Animal'> print type(run_kindof) <type 'function'>
dir():获取查询一个对象的所有属性和方法
In [1]: dir('ABC') ...: Out[1]: ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']