property函数
property() 函数的作用是在新式类中返回属性值。
用法
复制代码
1class property([fget[, fset[, fdel[, doc]]]])
参数
- fget -- 获取属性值的函数
- fset -- 设置属性值的函数
- fdel -- 删除属性值函数
- doc -- 属性描述信息
实例
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#定义一个可控属性值 x class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")
视频实例
复制代码
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#property 所有权 class Person(object): def __init__(self,age): #属性直接对外暴露 # self.age=age self._age = age # def getAge(self): # return self._age def setAge(self,age): if age<0: age=0 self._age=age #方法为受限制的变量去掉双下划线 @property def age(self): return self._age @age.setter #去掉下划线.setter def age(self,age): if age<0: age=0 self._age=age per=Person(18) # 直接暴漏不安全,没有数据过滤 # per.age=-10 # print(per.age) # per.setAge(15) # print(per.getAge()) per.age=-100#相当于调用setage print(per.age)#相当于调用getage #property 可以让你对受限制访问的属性使用点语法
动态添加属性
视频实例
复制代码
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#动态添加属性 #创建一个空类 # from types import MethodType # # class Person(object): # pass # #添加属性 # per=Person() # #动态添加属性,体现动态添加特点 灵活 # per.name='tom' # #d动态添加方法 # print(per.name) # # def say(self): # print("my name is "+self.name) # per.speak=MethodType(say,per) # per.speak() #------------------------------------- from types import MethodType class Person(object): __slots__ =("name","say","speak")#slots 插入 限制添加属性 #添加属性 per=Person() #动态添加属性,体现动态添加特点 灵活 per.name='tom' #d动态添加方法 print(per.name) def say(self): print("my name is "+self.name) per.speak=MethodType(say,per) #使用包添加函数 per.speak()
运算符
实例
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import operator print(1+2) print("1"+"2") #不同的类型用加法就会有不同解释 class Person(object): def __init__(self,num): self.num=num #运算符运算 def __add__(self, other): return Person(self.num+other.num) def __str__(self): return "num = "+str(self.num) per1=Person(1) per2=Person(1) print(per1+per2)
最后
以上就是冷酷宝贝最近收集整理的关于IOT python 高级培训(二)property函数动态添加属性运算符的全部内容,更多相关IOT内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复