类
在程序中:务必保证先定义类,后产生对象
这与函数的使用是类似的,先定义函数,后调用函数,类也是一样的,在程序中需要先定义类,后调用类。
不一样的是,调用函数会执行函数体代码返回的是函数体执行的结果,而调用类会产生对象,返回的是对象。
#先定义类 驼峰体
class Student:
# 1、变量的定义
stu_school = 'NUPG'
# 2、 功能的定义
def tell_stu_info(stu_obj):
pass
def set_info(stu_obj):
pass
print('hello world')
'''
hello world
'''
类体代码是在类定义阶段就会立即执行,会产生类的名称空间
属性访问的语法
#1、访问数据属性
print(Student.stu_school)
#2、访问函数属性
print(Student.tell_stu_info(11))
'''
NUPG
None
'''
产生对象
stu1 = Student() #通过类产生了一个对象,对象的个体属性为空
stu1.stu_name = '张三' #添加对象的属性
print(stu1.__dict__) #查看对象的属性
'''
{'stu_name': '张三'}
'''
但是如果产生了多个对象并且都需要添加属性,就会出现代码重复的现象
stu1 = Student() #通过类产生了一个对象,对象的个体属性为空
stu1.stu_name = '张三' #添加对象的属性
print(stu1.__dict__) #查看对象的属性
stu2 = Student()
stu2.stu_name = '丽丽'
print(stu2.__dict__)
stu3 = Student()
stu3.stu_name = '张'
print(stu3.__dict__)
__init__方法
解决上述问题:
解决方法一:通过定义函数,将重复功能简化
def init(obj, name, age, gender):
obj.stu_name = name
obj.stu_age = age
obj.stu_gender = gender
stu1 = Student()
init(stu1, 'egon', 18, 'male')
print(stu1.__dict__)
'''
{'stu_name': 'egon', 'stu_age': 18, 'stu_gender': 'male'}
'''
当时此类方法将类与函数的功能(设置对象属性)分开了,整合程度还不够高。
解决方法二:
class Student:
stu_school = 'NUPG'
def __init__(obj,name, age, gender): #功能名字一定要是__init__
obj.stu_name = name
obj.stu_age = age
obj.stu_gender = gender
def tell_stu_info(stu_obj):
pass
def set_info(stu_obj):
pass
obj1 = Student('egon', 18, 'male') #Student.__init__(空对象, )
print(obj1.__dict__)
'''
{'stu_name': 'egon', 'stu_age': 18, 'stu_gender': 'male'}
'''
调用类的过程有称之为实例化,发生了三件事:
1、先产生一个空对象
2、python会自动调用类中的__init__方法将空对象已经调用类时括号内传入的参数一同传给__init__方法
3、返回初始化完的对象
总结
1、会在调用类时自动触发执行,用来为对象初始化自己独有的数据
2、__init__内应该存放是为对象初始化属性的功能,但是也可以存放任意其他代码,想要在类调用时就立即执行的代码都可以放到该方法内
3、__init__方法必须返回None
属性查找
类的属性是共享给所有对象用的,大家访问的地址一样
obj1 = Student('egon', 18, 'male')
obj2 = Student('lili', 18, 'female')
obj3 = Student('dsb', 18, 'male')
print(id(obj1.stu_school))
print(id(obj2.stu_school))
print(id(obj3.stu_school))
'''
1718059633392
1718059633392
1718059633392
'''
如果通过修改类中的共用属性,其他对象的属性也会跟着修改
Student.stu_school = 'white cloud'
print(obj1.stu_school)
'''
white cloud
'''
如果通过对象去修改类中的属性,其他对象以及类中的属性不会修改
obj1.stu_school = 'white cloud'
print(obj1.stu_school)
print(Student.stu_school)
print(obj2.stu_school)
'''
white cloud
NUPG
NUPG
'''
类的函数属性是绑定给对象使用的,obj.method称为绑定方法,内存地址都不一样
print(OldboyStudent.learn)
print(s1.learn)
print(s2.learn)
print(s3.learn)
'''
<function OldboyStudent.learn at 0x1021329d8>
<bound method OldboyStudent.learn of <__main__.OldboyStudent object at 0x1021466d8>>
<bound method OldboyStudent.learn of <__main__.OldboyStudent object at 0x102146710>>
<bound method OldboyStudent.learn of <__main__.OldboyStudent object at 0x102146748>>
'''