lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

    • Python 基础

    • Python 数据库

    • 面向对象

      • 面向对象基础
      • 继承
      • slot
        • __slots__
      • @property
      • 多重继承
      • 枚举类
    • Python Web

    • Python 进阶

  • leetcode

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • python
  • 面向对象
2023-07-16
目录

slot

# __slots__

# 动态绑定

# 绑定属性

class Student:
    pass


s1 = Student()
## 绑定属性
s1.name = 'lv'
print('name:', s1.name)

# 绑定方法

from types import MethodType
## 动态绑定属性和方法

class Student:
    pass


s1 = Student()
s1.name = 'lv'
print('name:', s1.name)
s2 = Student()
s2.name = 'wang'



def set_name(self, name):
    self.name = name

## 给实例绑定一个方法
s1.set_name = MethodType(set_name, s1)
s1.set_name('lv123')
print('name:', s1.name)

## s2.set_name('wang123'), set_name 是 s1的方法,不能应用 s2上
## 给类绑定方法
def set_score(self, score):
    self.score = score


Student.set_score = set_score
s1.set_score(100)
print('score:', s1.score)
s2.set_score(88)
print('score:', s2.score)

# __slots__

class Student:
    __slots__ =  ['name', 'age']

s = Student()
s.name = 'lv'
s.age = 18
s.score = 88    ## 报错
继承
@property

← 继承 @property→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式