1. 程式人生 > >【python】繫結方法,__slots__使用

【python】繫結方法,__slots__使用

# -*- 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()