面向对象编程 Object Oriented Programming ,简称OOP,是一种程序设计思想,这种思想把对象作为程序的基本单元。
类是抽象的,对象是具体的,一种类包括其特定的数据或属性,以及操作数据的函数(方法)。
class Student(object):#Student是类 Class,Jack和Lisa是实例 Instance,也就是具体对象;括号里写的是这个新定义的类所继承的类,一般使用最大众的object类
def __init__(self,name,score): #用__init___方法来设置对象的属性 Property,属性即为参数,参数和函数参数相同
self.name=name #self表示创建的实例本身,所以在__init__方法内部,可以直接把各种属性绑定到self
self.score=score
def print_score(self): #这类对象对应的关联函数,称为类的方法 Method,只需要一个参数self即可调用封装在类里的数据
print('%s:%s' % (self.name,self.score))
Jack=Student('Jack Simpson',99) #创建实例要填好参数
Lisa=Student('Lisa Simpson',19)
Jack.score=98 #可以自由改变示例某一属性的具体值
Jack.city='Beijing' #也可以自由地给一个实例变量绑定属性,因此同一类的对象可能会有不同的属性
Jack.print_score()
Lisa.print_score()
print(Jack.city)
'''
Jack Simpson:98
Lisa Simpson:19
Beijing
'''
要让一个实例的属性不被外部访问,就需要在属性名前加上两个下划线__,这样就变成了私有变量,只有内部可以访问了,且这个变量在类中已经被视为_Student_score这样的格式了。
此时如果外部需要获取实例的属性,可以增加获取属性的方法,比如get_name或get_score。
若外部需要改变实例的属性,也可以增加改变的方法,比如 set_score( self , input )
设置访问限制,是为了避免传入无效的参数,在方法里对传入的参数进行检查,设置错误反馈。
class Animal(object):
def run(self):
print('Animal is running.')
def eat(self):
print('Animal is eating.')
class Dog(Animal):#编写子类 Subclss 时可以从父类继承,父类又称为基类 Base lass、超类 Super class
def run(self):#子类新建和父类同名的方法时,子类的方法会覆盖父类的方法,这就是多态
print('Dog is running.')
def eat(self):
print('Dog is eating.')
class Cat(Animal):
def run(self):
print('Cat is running.')
def eat(self):
print('Cat is eating.')
dog=Dog()
cat=Cat()
dog.run()
cat.run()
dog.eat()
cat.eat()
print(isinstance(dog,Animal))
print(isinstance(dog,Dog))
'''
Dog is running.
Cat is running.
Dog is eating.
Cat is eating.
True
True
'''
此外,多态还有其好处:
class Animal(object):
def run(self):
print('Animal is running.')
def eat(self):
print('Animal is eating.')
class Dog(Animal):
def run(self):
print('Dog is running.')
dog=Dog()
dog.run()
def run_twice(animal):
animal.run()
animal.run()
run_twice(Animal())
run_twice(Dog())
'''
Dog is running.
Animal is running.
Animal is running.
Dog is running.
Dog is running.
'''
由上例可知,对类和对象来说,同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果,这就是多态。
print(type(123))
print(type('qwe'))
print(type(1.111))
print(type([1,2,3]))
print(type((1,2,3,4)))
print(type(abs))#对函数使用时会返回对应的class类型
'''
'''
可以用来判断某一对象是否属于某一class类型:
class Life(object):
pass
class Animal(Life):
pass
class Monkey(Animal):
pass
monkey=Monkey()
dog=Animal()
print(isinstance(monkey,Monkey))
print(isinstance(monkey,Animal))
print(isinstance(monkey,Life))
print(isinstance(dog,Monkey))
'''
True
True
True
False
'''
能用type()判断的基本类型也可以用isinsistance()判断:
print(isinstance(123,int))
print(isinstance([1,2,3],list))
'''
True
True
'''
还可以判断一个变量是否是某些类型中的一种:
print(isinstance([1,2,3],(list,tuple)))
print(isinstance((1,2,3),(list,tuple)))
print(isinstance(123,(dict,set)))
'''
True
True
False
'''
print(dir('ABC'))#获取字符这一类的属性和方法
print(dir(123))#获取数字这一类的属性和方法
print(dir([1,2]))#获取列表这一类的属性和方法
print('qwe'.__len__())#等价于len('qwe')
class Human(object):
def __init__(self,age,height,weight):
self.century=21
self.age=age
self.height=height
self.weight=weight
def health(self):
return self.age*self.height/self.weight
man=Human(18,170,160)
print(hasattr(man,'century')) #判断man是否有century这种属性
print(man.century)
print(hasattr(man,'city'))
setattr(man,'city','Putian') #给man添加city这种属性,并设置为Putian
print(hasattr(man,'city'))
print(getattr(man,'city')) #获取man的city属性
print(man.city)
print(getattr(man,'homeland',404)) #获取man的homeland这一属性,若没有,则返回404
'''
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
3
True
21
False
True
Putian
Putian
404
'''