8.4 继 承
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
class Cat(Animal):
pass
dog = Dog()
dog.run()
cat = Cat()
cat.run()
执行结果:
Animal is running...
Animal is running...
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Dog(Animal):
def eat(self):
print('Eating ...')
dog = Dog()
dog.run()
dog.eat()
执行结果:
Animal is running...
Eating ...
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Animal(object):
def run(self):
print('Animal is running...')
def __run(self):
print('I am a private method.')
执行语句:
dog = Dog()
dog.__run()
执行结果:
Traceback (most recent call last):
File "D:/python/workspace/classextend.py", line 25, in <module>
dog.__run()
AttributeError: 'Dog' object has no attribute '__run'
class Animal(object):
def run(self):
print('Animal is running...')
def jump(self):
print('Animal is jumpping....')
def __run(self):
print('I am a private method.')
dog = Dog()
dog.run()
dog.jump()
cat = Cat()
cat.run()
cat.jump()
执行结果:
Animal is running...
Animal is jumpping....
Animal is running...
Animal is jumpping....
8.5 多 态
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('Cat is running...')
执行语句:
dog = Dog()
print('实例化Dog类')
dog.run()
cat = Cat()
print('实例化Cat类')
cat.run()
执行结果:
实例化Dog类
Dog is running...
实例化Cat类
Cat is running...
a = list() # a是list类型
b = Animal() # b是Animal类型
c = Dog() # c是Dog类型
print('a是否为list类型:', isinstance(a, list))
print('b是否为Animal类型:', isinstance(b, Animal))
print('c是否为Dog类型:', isinstance(c, Dog))
执行结果:
a是否为list类型: True
b是否为Animal类型: True
c是否为Dog类型: True
print('c是否为Dog类型:', isinstance(c, Dog))
print('c是否为Animal类型:',isinstance(c, Animal))
执行结果:
c是否为Dog类型: True
c是否为Animal类型: True
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
def run_two_times(animal):
animal.run()
animal.run()
run_two_times(Animal())
执行结果:
Animal is running...
Animal is running...
run_two_times(Dog())
执行结果:
Dog is running...
Dog is running...
run_two_times(Cat())
执行结果:
Cat is running...
Cat is running...
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Bird(Animal):
def run(self):
print('Bird is flying the sky...')
run_two_times(Bird())
执行结果:
Bird is flying the sky...
Bird is flying the sky...
8.6 封 装
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
std = Student('xiaozhi',90)
def info(std):
print('学生:%s;分数: %s' % (std.name, std.score))
info(std)
执行结果:
学生:xiaozhi;分数: 90
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Student0(object):
def __init__(self, name, score):
self.name = name
self.score = score
def info(self):
print('学生:%s;分数: %s' % (self.name, self.score))
stu = Student0('xiaomeng',95)
执行结果:
学生:xiaomeng;分数: 95
8.7 多重继承
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Animal(object):
pass
# 大类:
class Mammal(Animal):
pass
class Bird(Animal):
pass
# 各种动物:
class Dog(Mammal):
pass
class Bat(Mammal):
pass
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Runnable(object):
def run(self):
print('Running...')
class Flyable(object):
def fly(self):
print('Flying...')
class Dog(Mammal, Runnable):
pass
class Bat(Mammal, Flyable):
pass
8.8 获取对象信息
1. 使用type()函数
>>> type(123)
<class 'int'>
>>> type('abc')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>> type(abs)
<class 'builtin_function_or_method'>
>>> type(pri_pub) #上一节定义的PrivatePublicMethod类
<class '__main__.PrivatePublicMethod'>
>>> type(123)==type(456)
True
>>> type(123)==int
True
>>> type('abc')==type('123')
True
>>> type('abc')==str
True
>>> type('abc')==type(123)
False
>>> import types
>>> def func():
... pass
...
>>> type(fn)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> type(lambda x: x)==types.LambdaType
True
>>> type((x for x in range(10)))==types.GeneratorType
True
2. 使用isinstance()函数
>>> animal = Animal()
>>> dog = Dog()
>>> isinstance(dog, Dog)
True
>>> isinstance(dog, Animal)
True
>>> isinstance(dog, object)
True
>>> isinstance(dog, Dog) and isinstance(dog, Animal)
True
>>> isinstance(animal,Dog )
False
>>> isinstance([1, 2, 3], (list, tuple))
True
>>> isinstance((1, 2, 3), (list, tuple))
True
3. 使用dir()
>>> 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']
8.9 类的专有方法
1. __str__
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Student(object):
def __init__(self, name):
self.name = name
print(Student('xiaozhi'))
执行结果:
<__main__.Student object at 0x0000000000D64198>
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return '学生名称: %s' % self.name
print(Student('xiaozhi'))
执行结果:
学生名称: xiaozhi
>>> s = Student('xiaozhi')
>>> s
<__main__.Student object at 0x00000000030EC550>
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return '学生名称: %s' % self.name
__repr__ = __str__
在交互模式下执行:
>>> s = Student('xiaozhi')
>>> s
学生名称: xiaozhi
2. __iter__
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a、b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 100000: # 退出循环的条件
raise StopIteration();
return self.a # 返回下一个值
3. __getitem__
>>> Fib()[3]
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
Fib()[3]
TypeError: 'Fib' object does not support indexing
class Fib(object):
def __get分段模拟运行结果给出
最新发布