本文章由阿里云大学
和廖雪峰的python
整理。
使用__slots__
(浅学)
一般来说,我们创建class dog
就可以绑定属性和方法。
1 2 3 4 5 6
| class example: __slots__ = ("A","B") test1 = example() test1.A = 2 test1.C = 2
|
使用装饰器
装饰器是什么东西?
装饰器就是让程序员使用属性一样去使用方法
@property装饰get方法
property装饰器,用来将一个get方法,转换成对象的属性。
使用property装饰的方法,必须属性名是一样的
1 2 3 4 5 6 7 8 9 10 11
| class Person: def __init__(self,name): self.__name = name
def name(self): print("这是get方法") return self.__name
P1 = Person("阿福") print(P1.name())
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class Person: def __init__(self,name): self.__name = name @property def name(self): print("这是get方法") return self.__name
P1 = Person("阿福") print(P1.name)
|
@属性名.setter
装饰set方法
属性名要和property装饰的相对应
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Person: def __init__(self,name): self.__name = name @property def name(self): print("这是get方法") return self.__name @name.setter def name(self,name): self.__name = name
P1 = Person("阿福") print(P1.name) P1.name = "小璇" print(P1.name)
|