两大编程思想
- 面向过程:线性思维方式
- 面向对象:只找这个对象的参与者
类和对象
class Student: #student 就是类名,首字母大写
native_place='吉林' #直接写在类里的变量称为类属性 类属性 类属性
def __init__(self,name,age): #初始化方法
self.name=name
self.age=age
def eat(self): #实例方法
print('学生在吃饭')
def drink(self):
print('学生在喝水')
@staticmethod #这个是静态方法
def method(): #静态方法在()中不能使用self
print('我是静态方法')
@classmethod
def cm(cls):
print('我是类方法')
#创建Student的对象
stu1=Student('zhangsan','20')
stu1.eat() # #对象名.方法名()
print(stu1.name)##可以对实例属性进行输出
print(stu1.age)
print('----------类属性的使用方式------------')
Student.eat(stu1) ##这个同stu1.eat()的语句的功能相同
# #类名.方法名(类的对象)
print(Student.native_place)##可以对类属性进行输出
print(stu1.native_place) ##该输出依然是类属性的值
print('---------类方法的使用方式-------------')
Student.cm()
print('-----------静态方法的使用方式----------')
Student.method()
Student称为类对象
| native_place | 称为类属性,是在类中直接定义的变量 |
|---|---|
| stu1 | 称为Student类的对象 |
| classmethod | 称为类方法,是可以使用类名进行调用的,有个默认参数cls |
| staticmethod | 称为静态方法,是可以使用类名进行调用的,没有默认参数 |
动态绑定属性和方法
最后两段代码是动态属性和动态方法的语句
class Student:
def __init__(self,name,age): #定义Student类的初始方法
self.name=name
self.age=age
def eat(self):
print(self.name,'在吃饭。')
def drink(self):
print(self.name,'在喝水。')
'''
创建Student类的对象
'''
# 利用循环赋值
stuall=['zhangsan','lisi']
stuage=[20,30]
n=0
while n<2:
stu=Student(stuall[n],stuage[n])
stu.eat()
stu.drink()
n+=1
print('---------创建动态属性---------------')
stu1=Student('zhangsan',20)
stu2=Student('lisi',30)
##为stu1动态的绑定性别女
stu1.gender='女'
print(stu1.name,stu1.age,stu1.gender)
## 为stu1绑定动态函数
def show():
if stu1.age>50:
print('this man is old')
else:
print('this man is young')
stu1.show=show ##这个是动态绑定函数的语句要记住
stu1.show()
这篇博客介绍了面向过程和面向对象两种编程思想,重点讲解了面向对象中的类和对象概念,包括类属性、实例方法、类方法和静态方法的使用。通过示例展示了如何创建Student类,并创建对象stu1,演示了类方法、静态方法和动态绑定属性及方法的调用。动态绑定部分展示了如何为对象动态添加属性和方法,并进行调用。
1924

被折叠的 条评论
为什么被折叠?



