类与对象
1. 两大编程思想
2. 类和对象的创建
2.1 类
类别,分门别类,物以类聚:人类,鸟类,动物类,植物类,…
类是多个类似事物组成的群体的统称。能够帮助我们快速理解和判断事物的性质。
数据类型
- 不同的数据类型属于不同的类
- 使用内置函数查看数据类型
print(type(100)) <class ’ int’>
print(type(99)) <class ’ int’>
print(type(520)) <class ’ int’>
对象
100、99、520都是int类之下包含的相似的不同个例,这个个例专业术语称为实例或对象。
Python中一切皆对象
2.2 类的创建
创建类的语法
c
l
a
s
s
S
t
u
d
e
n
t
:
p
a
s
s
\textcolor{pink}{class} \quad \textcolor{green}{Student}\textcolor{pink}{:}\\ \quad \textcolor{blue}{pass}
classStudent:pass
class Student:
pass
# Python中一切皆对象
print(id(Student)) # 2108571567632
print(type(Student)) # <class 'type'>
print(Student) # <class '__main__.Student'>
类的组成
- 类属性
- 实例方法
- 静态方法
- 类方法
class Student: # Student是类的名称(类名),由一个或多个单词组成,每个单词首字母大写,其余小写
native_place='吉林' # 直接写在类里的变量,称为类属性
# 初始化方法
def __int__(self,name,age):
self.name=name # self.name称为实例属性,进行了一个赋值的操作,将局部变量的name值赋给实例属性
self.age=age
# 实例方法 (在类之外定义的叫函数,在内之内定义的叫做方法)
def eat(self):
print('学生在吃饭')
# 静态方法
@staticmethod
def method():
print('我使用了staticmethod进行修饰,所以我是静态方法')
# 类方法
@classmethod
def cm(cls):
print('我使用了classmethod进行修饰,所以我是类方法')
2.3 对象的创建
对象的创建又称为类的实例化
语法:
实例名=类名()
\textbf{\textcolor{bule}{实例名=类名()}}
实例名=类名()
例子:
stu=Student()
\textbf{\textcolor{green}{stu=Student()}}
stu=Student()
意义:
有了实例,就可以调用类中的内容。
# 创建Student类的对象
stu1=Student('jack',20)
print(id(stu1))
print(type(stu1))
print(stu1)
'''
print('---------------------------------------------')
print(id(Student))
print(type(Student))
print(Student)
'''
stu1.eat() # 对象名.方法名
print(stu1.name)
print(stu1.age)
print('---------------------------------------------')
Student.eat(stu1) # 类名.方法名(类的对象)-->实际上就是方法定义处的self
# 40 行和35行代码功能相同都是调用Student中的eat方法
3. 类属性、类方法、静态方法
3.1 类属性
类中方法外的变量称为类属性,被该类的所有对象共享。
print('-----------类属性的使用方式---------------')
print(Student.native_place)
stu1=Student('张三',20)
stu2=Student('李四',30)
print(stu1.native_place)
print(stu2.native_place)
Student.native_place='天津'
print(stu1.native_place)
print(stu2.native_place)
3.2 类方法
使用@classmethod修饰的方法,使用类名直接访问的方法。
print('-----------类方法的使用方式---------------')
Student.cm()
3.3 静态方法
使用@staticmethod修饰的方法,使用类名直接访问的方法。
print('-----------静态方法的使用方式---------------')
Student.method()
3.4 动态绑定属性和方法
Python是动态语言,在创建对象之后,可以动态地绑定属性和方法。
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print(self.name+'在吃饭')
'''一个Student类可以创建N多个Student类的实例对象,每个实例对象的属性值可以不同'''
stu1=Student('张三',20)
stu2=Student('李四',30)
print(id(stu1))
print(id(stu2))
'''为stu1动态地绑定属性'''
stu1.gender='女'
print(stu1.name,stu1.age,stu1.gender)
print(stu2.name,stu2.age)
# print(stu2.name,stu2.age,stu2.gender) 报错 没有为stu2绑定gender
print('---------------------------')
stu1.eat()
stu2.eat()
'''为stu1动态地绑定方法'''
def show():
print('定义在类之外的称为函数')
stu1.show=show
stu1.show()
# stu2.show() 报错 没有为stu2绑定show方法