【python】【学习】绑定方法,__slots__使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012335044/article/details/83508243
# -*- coding:utf-8 -*-

from types import MethodType

# 1.为了给所有实例都绑定方法,可以给class绑定方法:注:无法使用私有变量
# 2.实例绑定方法
# 3.使用 __slots__ 限制实例属性。注:使用后无法添加实例方法

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score
    __slots__ = ('name', 'score')   # 使用 __slots__限制实例的属性


def welcome(self):
    print('welcome new times ', self.name)

def black(self):
    print('luky boy !')

Student.welcome = welcome

std1= Student('zzk',99)

# print(std1.name)
std1.welcome()

std1.black = MethodType(black, std1)    #给实例绑定方法
std1.black()

使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__

猜你喜欢

转载自blog.csdn.net/u012335044/article/details/83508243