前言
python学习笔记day4 (仅供学习使用)
一、面向对象、面向过程
二、定义python中的类
class Student: #Student为类的名称(类名)由一个或多个单词组成,每个单词的首字母大写,其余小写
pass
#Python中一切皆对象Student是对象吗?内存有开空间吗?
print(id(Student)) #2926222013040
print(type(Student)) #<class 'type'>
print(Student) #<class '__main__.Student'>
1.类的组成
类属性、实例方法、静态方法、类方法
class Student: #Student为类的名称(类名)由一个或多个单词组成,每个单词的首字母大写,其余小写
native_pace='吉林' #直接写在类里的变量,称为类属性
def __init__(self,name,age):
self.name=name #self.name 称为实体属性 ,进行了 一个赋值的操作,将局部变量的name的值赋给实体属性
self.age=age
#实例方法
def eat(self):
print('学生在吃饭...')
#静态方法
@staticmethod
def method():
print('我使用了statticmethod进行修饰,所以我是静态方法')
#类方法
@classmethod
def cm(cls):
print('我是类方法,因为我使用了classmethod进行修饰')
#在类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')
三、对象的创建
class Student: #Student为类的名称(类名)由一个或多个单词组成,每个单词的首字母大写,其余小写
native_pace='吉林' #直接写在类里的变量,称为类属性
def __init__(self,name,age):
self.name=name #self.name 称为实体属性 ,进行了 一个赋值的操作,将局部变量的name的值赋给实体属性
self.age=age
#实例方法
def eat(self):
print('学生在吃饭...')
#静态方法
@staticmethod
def method():
print('我使用了statticmethod进行修饰,所以我是静态方法')
#类方法
@classmethod
def cm(cls):
print('我是类方法,因为我使用了classmethod进行修饰')
#在类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')
#创建Student类的对象
stu1=Student('张三',20)
print(id(stu1))
print(type(stu1))
print(stu1)
print('---------------------')
print(id(Student)) #Student是类的名称
print(type(Student))
print(Student)
运行:
140579159453360
<class '__main__.Student'>
<__main__.Student object at 0x7fdb22dcaeb0>
---------------------
140579144006592
<class 'type'>
<class '__main__.Student'>
四、类属性,类方法,类静态方法
类同上
#类属性的使用方式
#print(Student.native_pace)
stu1=Student('张三',20)
stu2=Student('李四',30)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace='天津'
print(stu1.native_pace)
print(stu2.native_pace)
print('---------类方法的使用方式------------------')
Student.cm()#类方法的使用方式,使用类名去掉用的
print('---------静态方法的使用方式------------------')
Student.method()
五、动态绑定属性和方法
python是动态语言,在创建对象后,可以动态的绑定属性和方法
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print(self.name+'在吃饭')
stu1=Student('张三',20)
stu2=Student('李四',30)
print(id(stu1))
print(id(stu2))
print('------------为stu2动态绑定性别属性---------------------------')
stu1.gender='女'
#print(stu1.name,stu1.age,stu1.gender)
print(stu1.name,stu1.age,stu1.gender)
print(stu2.name,stu2.age)
print('--------------------------')
stu1.eat()
stu2.eat()
def show():
print('定义在类之外的,称函数')
stu1.show=show
stu1.show()
#stu2.show() #因为stu2并没有绑定show方法
运行:
140586825403552
140586825592352
------------为stu2动态绑定性别属性---------------------------
张三 20 女
李四 30
--------------------------
张三在吃饭
李四在吃饭
定义在类之外的,称函数