我是靠谱客的博主 任性灯泡,这篇文章主要介绍【Python 29】动态绑定属性和方法,现在分享给大家,希望可以做个参考。

一个 Student 类可以创建 N 个Student类的实例对象,每个实例对象的属性值不同。

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 作 者:要努力,努力,再努力 # 开发日期:2022/4/23 14:32 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), id(stu2)) print('-------------------动态绑定属性----------------------') stu2.gender = '女' print(stu1.name, stu1.age) # print(stu1.name, stu1.age, stu1.gender) # AttributeError: 'Student' object has no attribute 'gender' print(stu2.name, stu2.age, stu2.gender) print('--------------------------------------') stu1.eat() stu2.eat() def show(): print('定义在类之外,是函数') print('-------------------动态绑定方法----------------------') stu1.show = show stu1.show() # stu2.show() # AttributeError: 'Student' object has no attribute 'show'

最后

以上就是任性灯泡最近收集整理的关于【Python 29】动态绑定属性和方法的全部内容,更多相关【Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部