OPP
Object Oriented Programming
定义类 class 并实例化
class Student(object): # 通过 class 定义
def __init__(self,name,score): # 初始化 self 必填,其余为属性参数
self.name = name
self.score = score
bart = Student('Bob',59) # 将类实例化(必须传入__init__函数的参数) 赋给变量,此时bart为实例
print(bart.name,':',bart.score)
数据封装–方法
将传入的数据通过内部的函数(方法),自身调用,将数据封装在方法中,对于方法调用只有一个接口,无须知道内部实现细节,具有安全隐蔽性
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))
bart = Student('Bob',59)
bart.print_score()
私有变量 private
在属性前加上__
使成为__xxxx
私有变量
此时无法类外部直接访问和修改
class Student1(object):
def __init__(self,name,score):
self.__name = name # 私有属性
self.__score = score
def print(self):
print('%s : %s' % (self.__name, self.__score))
haha = Student1('Ahang',90)
print(haha.__score) # 无法直接访问私有成员,会报错
haha.__score = 50 # 无法修改
haha.print() # print()方法是可以调用的,是公共方法
外部访问私有变量
def get_name(self):
return self.__name
def get_score(self):
return self.__score
外部修改私有变量
def set_score(self,score):
self.__score = score
原先也可以直接修改,为何需要定义私有再修改呢?
这样可以在方法内检查参数合法性
class Student(object):
...
def set_score(self, score): # 检查参数
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')
__score
私有变量实际上是改变了名称_Student1__score
,所以也是可以直接访问
haha._Student1__score = 60
直接修改了私有变量
继承和多态
定义一个class
类时,可以从现有的class
中继承,新的class
称为子类,原有的class
称为父类、基类
父类
class Animal(object):
def run(self):
print('Animal is running...')
子类继承父类:Dog(Animal)
class Dog(Animal): # 直接继承了run方法,无须写
pass
class Cat(Animal):
def run(self): #
print('cat is running...')
dog = Dog()
dog.run()
Cat().run()
这就是多态的意思:
对于一个变量,我们只需要知道它是Animal
类型,无需确切地知道它的子类型,就可以放心地调用run()
方法,而具体调用的run()
方法是作用在Animal、Dog、Cat
还是Tortoise
对象上,由运行时该对象的确切类型决定,这就是多态真正的威力:调用方只管调用,不管细节,而当我们新增一种Animal
的子类时,只要确保run()
方法编写正确,不用管原来的代码是如何调用的。
获取对象信息
优先使用isinstance()
type(abs) | 不考虑继承关系,父子不同 | 返回对象类型 |
---|---|---|
isinstance('str',str) | 考虑继承关系,父子相同 | 判断类型是否相同 |
class A:
pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
通过type
判断数据类型
>>> type('abc')==str # 基本数据类型
True
>>> type('abc')==type(123)
False
>>> import types # 对于函数、列表等用 types
>>> def fn():
... 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
dir() 获取对象所有的属性和方法
hasattr(instancename, 'attribute') | 判断是否存在某属性 |
---|---|
getattr(instancename, 'attribute',404) | 获取某属性,如果没有返回404 |
setattr(instancename, 'attribute',10) | 设置新属性到实例中,并设置属性值 |
class MyObject(object): # 定义类
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject() # 实例化
print(hasattr(obj,'x')) # 判断属性存在
print(obj.x)
print(hasattr(obj,'y'))
setattr(obj,'y',19) # 设置属性
print(hasattr(obj,'y'))
print(getattr(obj,'y',404)) # 获取属性,若没有该属性返回404