面向对象是一门编程思想python
类指的是类型,一系列对象之间相同的特征与技能的结合体编程
在现实世界中,先有对象再定义出类,类是抽象产生的,对象是实际存在的函数
在程序中,必须先定义类,而后再调用类获得返回值获得对象学习
先从现实世界中经过对象来总结出类,而后再定义类,经过调用类来产生对象大数据
语法:class + 类的名字:(类名要是驼峰体)设计
对象之间相同的特征(数据属性,变量)code
对象之间相同的技能(类中的方法,函数)对象
调用类的过程称为类的实例化,产生的对象也能够称为类的一个实例内存
调用类产生对象时发生的事情:it
# 定义一个People类名,注意使用驼峰体 class People: country = '中国' def __init__(self,name,age,sex): # 给对象添加新属性 self.age = age self.name = name self.sex = sex #类里面定义函数默认会传入一个self当形参 def learn(self): print('学习技能') p1 = People('shen', 18, 'male') print(p1.name) # shen print(p1.age) # 18 print(p1.sex) # male #直接经过类来调用类中的函数须要传入任意一个参数给self People.learn(111) #经过对象来调用类中的函数,不须要传入参数,由于对象会被当作参数传入 p1.learn()
经过类.__ dict __ 或 对象.__ dict__ 查看类与对象的名称空间,也能够经过.__ dict __['类或对象中的名字']直接查看值
# # 定义一个People类名,注意使用驼峰体 class People: country = '中国' def __init__(self,name,age,sex): self.age = age self.name = name self.sex = sex #类里面定义函数默认会传入一个self当形参 def learn(self): print('学习技能') p1 = People('shen', 18, 'male') print(p1.__dict__) # {'age': 18, 'name': 'shen', 'sex': 'male'} print(p1.__dict__['age']) # 18 print(People.__dict__) # {'__module__': '__main__', 'country': '中国', '__init__': <function People.__init__ at 0x000002CCD9AC2B88>, 'learn': <function People.learn at 0x000002CCD9AC6DC8>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None} print(People.__dict__['country']) # 中国 print(People.__dict__['learn']) # <function People.learn at 0x0000015CFB1A6DC8>
class People: country = '中国' def __init__(self,name,age,sex): self.age = age self.name = name self.sex = sex #类里面定义函数默认会传入一个self当形参 def learn(self): print('学习技能') p1 = People('shen', 18, 'male') # 查 print(p1.country) # 中国 # 改 p1.country = 'China' print(p1.country) # China # 删 del p1.sex print(p1.sex) # 删除后报错 # 增 People.salary = 150000000000 print(People.salary) # 150000000000 print(p1.salary)# 150000000000
p1 = People('shen', 18, 'male') p2 = People('shen1', 19, 'male') p3 = People('shen2', 20, 'male') print(p1.country, id(p1.country)) # 中国 1853896576144 print(p2.country, id(p2.country)) # 中国 1853896576144 print(p3.country, id(p3.country)) # 中国 1853896576144 调用类中的方法,id相同,只是传入的对象给self不一样因此方法不一样 print(People.learn, id(People.learn)) # <function People.learn at 0x000002A39FF26DC8> 2901786389960 print(p1.learn, id(p1.learn)) #<bound method People.learn of <__main__.People object at 0x00000153E75690C8>> 1459724834120 print(p2.learn, id(p2.learn)) #<bound method People.learn of <__main__.People object at 0x00000153E73BF708>> 1459724834120 print(p3.learn, id(p3.learn)) #<bound method People.learn of <__main__.People object at 0x00000153E73BF588>> 1459724834120
由对象来调用类里面的函数称为对象的绑定方法
对象的绑定方法的特殊之处:
对象.属性:先从对象自身的名称空间中查找——》类的名称空间中查找——》再找不到会报错
用type方法打印出有
str1 = '沈' print(type(str1)) # <class 'str'> list1 = [1, 2, 3] print(type(list1)) # <class 'list'>