编程的两大思想:面向过程和面向对象
类的创建
创建类的语法:
class 类名: #类名由一个或多个单词组成,每个单词的首字母大写,其余小写
pass
例:
class A:
pass
#Python中一切皆对象
print(id(A))
print(type(A))
print(A)
类的组成:类属性、实例方法、静态方法、类方法
类属性:类中方法外的变量,即直接写在类里的变量称为类属性,被该类的所有对象所共享,使用类名.类属性调用
实例方法:在类之内定义的称为方法,在类之外定义的称为函数
静态方法:使用***@staticmethod修饰的方法,使用类名直接访问的方法
类方法:使用@classmethod***修饰的方法,使用类名直接访问的方法
例:
class Student:
narive_place='北京' #类属性
# 初始化方法
def __init__(self,name,age):
self.name=name #赋值操作 self.name称为实体属性,将局部变量name的值赋给实体属性
self.age=age
#实例方法 self必须写
def eat(self):
print('学生在吃饭···')
#静态方法
@staticmethod
def method():
print('我使用了staticmethod进行修饰,所以我是静态方法')
#类方法
@classmethod
def cm(cls):
print('我是类方法,因为我使用了classmethod进行修饰')
对象的创建:实例名=类名()
对象的创建又称为类的实例化,有了实例就可以调用类中的内容:对象名/类名.方法名()
例:
stu1=Student('张三',20)
print('-------实例对象信息-------')
print(id(stu1))
print(type(stu1))
print(stu1)
print('-------类对象信息---------')
print(id(Student))
print(type(Student))
print(Student)
#创建后的对象可以使用类中的方法
print('-------调用类中的方法---------')
stu1.eat() #对象名.方法名()
Student.eat(stu1) #类名.方法名(类的对象)-->实际上就是方法定义处的self
print(stu1.name)
print(stu1.age)
类属性的调用:对象名/类名.类属性
print('----------类属性的调用------------')
print(Student.narive_place)
stu2=Student('李四',19)
stu3=Student('王五',21)
print(stu2.narive_place)
print(stu3.narive_place)
Student.narive_place='上海'
print(stu2.narive_place)
print(stu3.narive_place)
类方法的使用方式:类名.类方法名
Student.cm()
静态方法的使用方式:类名.静态方法名
Student.method()
动态绑定属性和方法:对象名.动态绑定的属性名/方法名=属性/方法
Python是动态语言,在创建对象之后可以动态地绑定属性和方法,只针对当前对象起作用
例:
#创建类
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print(self.name+'在吃饭')
#创建对象 一个Student类可以创建多个Student类的实例对象,每个实例对象的属性值可以不同或相同
stu1=Student('张三',20)
stu2=Student('李四',19)
print('-----为stu1动态绑定性别属性-----')
stu1.gender='男'
print(stu1.name,stu1.age,stu1.gender)
print(stu2.name,stu2.age)
# print(stu2.name,stu2.age,stu2.gender) #AttributeError: 'Student' object has no attribute 'gender'
stu1.eat()
stu2.eat()
print('-----动态绑定方法-----')
def show():
print('定义在类之外的称为函数')
stu1.show=show()
stu1.show
# stu2.show #AttributeError: 'Student' object has no attribute 'show'
运行结果: