python学习日记(8)

  • slots
  • property与property

slots

如果有

class Student:
    pass

又有

def set_age(self, age):
    self.age = age

from types import MethodType
s = Student()
s.set_age = types(set_age, s)

如果需要限制绑定的属性则需要

def Student:
    __slots__ = ("name", "age")

以后就只能绑定name,age两个属性了


property()与@property

property函数的原型如下:

property(fget = None,fset = None,fdel = None,doc = None)

如果有

class Stu():
    """test property"""
    def __init__(self, name):
        self.age = None
        self.name = name
    @property
    def get_name(self):
        print("execute")
        return self.name

python学习日记(8)_第1张图片

把一个方法变成了属性


如果有

class Stu():
    """test property"""
    def __init__(self):
        self.age = None
    def set_age(self, age):
        self.age = age
    def get_age(self):
        return self.age
    def del_age(self):
        del self.age
    a = property(get_age, set_age, del_age, "test")

可以直接使用


也可以

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

你可能感兴趣的:(我的学习日记,python)