本文章由阿里云大学廖雪峰的python整理。

使用__slots__(浅学)

一般来说,我们创建class dog就可以绑定属性和方法。

1
2
3
4
5
6
class example:
__slots__ = ("A","B") #那么该类只能使用“A”,“B”两种属性

test1 = example()
test1.A = 2 # A属性可以使用
test1.C = 2 # C属性不可以使用,此语句也会报错

使用装饰器

装饰器是什么东西?

装饰器就是让程序员使用属性一样去使用方法

@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
#使用property
#可以像使用属性一样去使用方法
class Person:
def __init__(self,name):
self.__name = name

#get方法(获取值)
@property
def name(self):
print("这是get方法")
return self.__name

P1 = Person("阿福")
print(P1.name) #区别在这,不使用P1.name()

@属性名.setter装饰set方法

属性名要和property装饰的相对应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#使用 @属性名.setter
#注意属性名,这里我们要对应上面property装饰的name
class Person:
def __init__(self,name):
self.__name = name
@property
def name(self):
print("这是get方法")
return self.__name

# setter方法(设置值)
@name.setter
def name(self,name):
self.__name = name

P1 = Person("阿福")
print(P1.name)
P1.name = "小璇" # 在这里可以像属性一样赋值
print(P1.name)