一、两大编程思想
二、类与对象(python中一切皆对象)
1、类:类是多个类似事物组成的群体的统称。能够帮助我们快速理解和判断事物的性质。
2、对象:100,99等都是int类之下包含的相似的不同个例,这个个例专业术语称为实例或对象。
三、类的创建
1、类的组成
- 类属性
- 实例方法
- 静态方法
- 类方法
class Student: #Student为类名,有一个或者多个单词组成,每个单词的首字母大写,其余小写
native_place='陕西' #直接写在类里的变量,称为类属性
def __init__(self,name,age):
self.name=name #self.name 称为实体属性,进行了赋值的操作,将局部变量Name的值赋给实体属性,
self.age=age
def eat(self): #实例方法 在类之外定义的称为函数,在类之内定义的称为实例方法
print('在吃饭')
@staticmethod #静态方法
def method():
print('我使用了staticmethod进行修饰,所以我是静态方法')
@classmethod #类方法
def cls(cls):
print('类方法')
2、类属性
类中方法外的变量称为类属性,被该类的所有对象所共享
stu1=Student('张三',20)
print(stu1.native_place) #陕西
3、类方法
使用@classmethod修饰的方法,使用类名直接访问的方法
Student.cls() #类方法
4、静态方法
使用@staticmethod修饰的方法,使用类名直接访问的方法
Student.method() #我使用了staticmethod进行修饰,所以我是静态方法
四、对象的创建
对象的创建又称为类的实例化
stu1=Student('张三',20) #创建Student类的对象
#以下两行代码功能相同,都是调用Student中的eat方法
stu1.eat() #在吃饭 对象名.方法名()
Student.eat(stu1) #在吃饭 类名.方法名(类的对象)
五、动态绑定属性和方法
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print(self.name+'在吃饭')
stu1=Student('张三',20)
stu2=Student('李四',18)
#为stu2绑定性别属性 只有stu2有,stu1没有
stu2.gender='女'
#为stu2绑定方法
def show():
print('定义在类之外的函数')
stu2.show=show
stu2.show() #定义在类之外的函数
stu1.show() #AttributeError: 'Student' object has no attribute 'show'