python基础 -- slots

1. 作用

限定属性个数和名称

2. 操作

# slots
# 限定属性

# 原代码
class Student(object):
    
    def __init__(self, name):
        self.__name = name

    def __str__(self):
        return 'so boring! {}.'.format(self.__name)

# s = Student('Tommy')
# print(s)
# s.age = 25
# print(s.age)
# s.score = 89
# print(s.score)
# so boring! Tommy.
# 25
# 89

class Teacher(object):

    __slots__ = ('__name','age', 'gender') # 
    
    def __init__(self, name):
        self.__name = name

    def __str__(self):
        return '{} so boring~~!'.format(self.__name)

t = Teacher('Maria')
print(t)
t.age = 25
print(t.age)
t.gender = '男'
print(t.gender)
# t.score = 100
# print(t.score)

你可能感兴趣的:(python基础 -- slots)