中国城乡与建设部网站,做家具定制的设计网站,微信小程序登陆wordpress后台,淄博周村网站建设报价面向对象编程 Object Oriented Programming #xff0c;简称OOP#xff0c;是一种程序设计思想#xff0c;这种思想把对象作为程序的基本单元。类是抽象的#xff0c;对象是具体的#xff0c;一种类包括其特定的数据或属性#xff0c;以及操作数据的函数#xff08;方法…面向对象编程 Object Oriented Programming 简称OOP是一种程序设计思想这种思想把对象作为程序的基本单元。类是抽象的对象是具体的一种类包括其特定的数据或属性以及操作数据的函数方法。类和实例class Student(object):#Student是类 ClassJack和Lisa是实例 Instance也就是具体对象括号里写的是这个新定义的类所继承的类一般使用最大众的object类def __init__(self,name,score): #用__init___方法来设置对象的属性 Property属性即为参数参数和函数参数相同self.namename #self表示创建的实例本身所以在__init__方法内部可以直接把各种属性绑定到selfself.scorescoredef print_score(self): #这类对象对应的关联函数称为类的方法 Method只需要一个参数self即可调用封装在类里的数据print(%s:%s % (self.name,self.score))
JackStudent(Jack Simpson,99) #创建实例要填好参数
LisaStudent(Lisa Simpson,19)
Jack.score98 #可以自由改变示例某一属性的具体值
Jack.cityBeijing #也可以自由地给一个实例变量绑定属性因此同一类的对象可能会有不同的属性
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 classdef 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.)
dogDog()
catCat()
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.)
dogDog()
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.
由上例可知对类和对象来说同一操作作用于不同的对象可以有不同的解释产生不同的执行结果这就是多态。获取对象信息使用type()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 int
class str
class float
class list
class tuple
class builtin_function_or_method
使用isinstance()可以用来判断某一对象是否属于某一class类型class Life(object):pass
class Animal(Life):pass
class Monkey(Animal):pass
monkeyMonkey()
dogAnimal()
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
使用dir()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.century21self.ageageself.heightheightself.weightweightdef health(self):return self.age*self.height/self.weight
manHuman(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