python 给实例和类绑定属性和方法

#定义一个类
class Student():
    pass

stu1 = Student()
# 1.我们给对象 stu1绑定一个属性 name
stu1.name = 'Jack'
print(f'stu1.name = {stu1.name}')
# 再绑定一个方法
def set_age(self, age):
    self.age = age

from types import MethodType # MethodType类是用来将外部方法和属性绑定到类或者实例上
stu1.set_age = MethodType(set_age, stu1)
stu1.set_age(24)
print(f"stu1.age = {stu1.age}")

# 以上只能将属性或者方法绑定到具体的实例上,换个实例这些就都没有了

# 2.将方法绑定到类上
def set_score(self, score):
    self.score = score

# Student.set_score = set_score  #方式一
Student.set_score = MethodType(set_score, Student)  # 方式二
stu2 = Student()
stu2.set_score(90)
print(f"stu2.score = {stu2.score}")
# 动态绑定允许我们在程序运行的过程中动态给class加上功能

# 3.如果要限制实例属性,比如只能个Student实例添加 name 和 age 属性
# 这个时候就要在定义类的时候,加一个特殊的变量
# __slots__
class Teacher():
    __slots__ = ('name', 'age') #用 tuple 定义允许绑定的属性名称
    pass

tech1 = Teacher()
tech1.name = 'Tom'
tech1.age = 22
# tech1.gender = 'Man' #报错 AttributeError: 'Teacher' object has no attribute 'gender'

# 注意 : __slots__属性只对当前类实例有作用,对继承的子类没有作用
# 如果子类也定义了 __slots__,那么子类的就是父类定义的加上子类定义的

# 4. Python内置的@property装饰器
# @property的一个最直接的作用就是把类方法变为类属性,访问这些方法的返回值时就不用多写个括号了
# @property其实就相当于get方法,之后的@属性名.setter就相当于set方法

class Student_():
    @property
    def score(self):
        return self.score_ # 这里注意 实例属性 score_ 一定不能和 方法 score同名,不然会报错

    @score.setter
    def score(self, score):
        if not isinstance(score, int):
            raise ValueError("score must be an integer")
        if score < 0 or score > 100:
            raise ValueError(f"score {score} out of range (0 ~ 100)")
        self.score_ = score

stu_1 = Student_()
stu_1.score = 99 # 这里注意,实际是调用的方法 score,因为用 @property装饰了之后,对外感觉是调用的实例属性
print(f'stu_1.score = {stu_1.score}')
发布了80 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qiukapi/article/details/104558085
今日推荐