快乐的鲸鱼

Python 面向对象学习笔记

2015/12/04

定义类

1
2
3
4
5
6
7
8
class Student(object):

def __init__(self, name, score):
self.name = name
self.score = score

def print_score(self):
print('%s: %s' % (self.name, self.score))

以上的类的定义中,Student是类名,object是所继承的父类。

使用类对象

1
2
3
Bob = Student('Bob', 56)
Bob.name
Bob.score

self可省略,python自动加入

继承和多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Animal(object):
def run(self):
print('Animal is running...')

class Cat(Animal):
pass

class Dog(Animal):
def run(self):
print('Dog is running...')

cat = Cat()
cat.run()

dog = Dog()
dog.run()

运行结果如下:

1
2
Animal is running...
Dog is running...

静态语言 vs 动态语言

对于静态语言(例如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类,否则,将无法调用run()方法。

对于Python这样的动态语言来说,则不一定需要传入Animal类型。我们只需要保证传入的对象有一个run()方法就可以了:

获取对象类型

使用type()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>>type(123)
<class 'int'>

>>>type('str')
<class 'str'>

>>>type(None)
<type(None) 'NoneType'>

>>>type(abs)
<class 'builtin_function_or_method'>

>>> type(123)==type(456)
True


>>> import types
>>> def fn():
... pass
...
>>> type(fn)==types.FunctionType
True

使用isinstance()

1
2
3
4
5
6
7
8
>>> a = Animal()
>>> d = Dog()

>>> isinstance(d, Dog)
True

>>> isinstance(d, Animal)
True

使用dir()

如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

1
2
>>> dir('ABC')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
CATALOG
  1. 1. 定义类
  2. 2. 使用类对象
  3. 3. 继承和多态
  4. 4. 静态语言 vs 动态语言
  5. 5. 获取对象类型
    1. 5.1. 使用type()
    2. 5.2. 使用isinstance()
    3. 5.3. 使用dir()