类
类:具有相同属性和技能的一类事物
class Person:
'''类体:两部分:变量部分,方法(函数)部分'''
mind = '有思想' # 变量,属性,静态变量,静态字段
animal = '高级动物'
faith = '有信仰'
def __init__(self,name,age,hobby):
self.name = name # 相当于Person.money = '运用货币' #动态变量、动态属性
self.age = age
self.hobby = hobby
def work(self): # 方法,函数,动态变量
print('%s会工作...' %self.name)
def shop(self):
print('人类可以消费....')
对象
对象: 具体的类的表现,具体的实实在在的一个实例
p = Person()
操作类
类名的角度
Person.__dict__
查询类中的所有内容(不可进行增删改查操作)
>>> print(Person.__dict__)
{'__module__': '__main__', '__doc__': '类体:两部分:变量部分,方法(函数)部分', 'mind': '有思想', 'animal': '高级动物', 'faith': '有信仰', '__init__': <function Person.__init__ at 0x03470390>, 'work': <function Person.work at 0x03470348>, 'shop': <function Person.shop at 0x03470300>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>}
>>> print(Person.__dict__['faith'])
有信仰
- 万能的
.
对类中的单个的变量进行增删改查
>>> print(Person.animal) #查
高级动物
>>> Person.money = '运用货币' #增
>>> print(Person.__dict__)
{'__module__': '__main__', '__doc__': '类体:两部分:变量部分,方法(函数)部分', 'mind': '有思想', 'animal': '高级动物', 'faith': '有信仰', '__init__': <function Person.__init__ at 0x03470390>, 'work': <function Person.work at 0x03470348>, 'shop': <function Person.shop at 0x03470300>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, 'money': '运用货币'}
# 查看结果,类中新增了一个money属性(字段)
>>> Person.mind = '无脑的' #改
>>> print(Person.mind)
无脑的 #mind属性被修改
>>> del Person.mind #删
>>> print(Person.__dict__)
{'__module__': '__main__', '__doc__': '类体:两部分:变量部分,方法(函数)部分', 'animal': '高级动物', 'faith': '有信仰', '__init__': <function Person.__init__ at 0x03470390>, 'work': <function Person.work at 0x03470348>, 'shop': <function Person.shop at 0x03470300>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, 'money': '运用货币'}
# 查看结果,类中的mind属性被删除
对象角度
对象名.__dict__
,查询对象中的所有的内容(只能查询)
>>> p = Person('张三','23','羽毛球')
>>> p.__dict__
{'name': '张三', 'age': '23', 'hobby': '羽毛球'}
对象名.属性名(方法)
,万能的点(可以增删改查)
>>> p.name #查
'张三'
>>> p.sex = '女' #增
>>> p.__dict__
{'name': '张三', 'age': '23', 'hobby': '羽毛球', 'sex': '女'}
>>> p.name = '白百何' #改
>>> p.__dict__
{'name': '白百何', 'age': '23', 'hobby': '羽毛球', 'sex': '女'}
>>> del p.hobby #删
>>> p.__dict__
{'name': '白百何', 'age': '23', 'sex': '女'}