1.动态绑定属性和方法
与Javascript类似,python允许给对象动态添加属性和方法。但是,给一个对象动态绑定的属性和方法,对另一个对象是不起作用的。
为了给所有实例都绑定方法,可以给class绑定属性和方法。
实例:
# -*- coding: utf-8 -*-
# @Time : 2022/4/8 15:39
# @File : slots.py
# @Software : PyCharm
from types import MethodType
class Person(object):
pass
p1 = Person()
p2 = Person()
def study(self): # 定义一个函数作为实例方法
print(self.name, "is good good study,day day up!")
def hello(self):
if hasattr(self, 'name'):
print('my name is:', self.name, 'my age is:', self.age)
else:
print('hello,my age is:', self.age)
p1.name = '张三'
p1.study = MethodType(study, p1)
print(p1.name)
p1.study()
# 给一个实例动态绑定的属性和方法,在另一个实例是不起作用的
# print(p2.name) # p2没有name属性
# p2.study() #错误,p2没有study()方法
# 使用class绑定属性和方法
Person.age = 18
Person.sayHello = hello;
p1.sayHello()
p2.sayHello()
允许结果:
张三
张三 is good good study,day day up!
my name is: 张三 my age is: 18
hello,my age is: 18
2.使用__slots__
如果我们想要限制实例的属性怎么办?比如,只允许对Person实例添加name和age属性和study方法。
# -*- coding: utf-8 -*-
# @Time : 2022/4/8 15:39
# @File : slots.py
# @Software : PyCharm
from types import MethodType
class Person(object):
__slots__ = ('name', 'age', 'study') # 用tuple定义允许绑定的属性或者方法的名称
def study(self): # 定义一个函数作为实例方法
print(self.name, "is good good study,day day up!")
p1 = Person()
p1.name = '张三'
p1.study = MethodType(study, p1)
p1.study()
# 不能添加school属性
# p1.school = '西安电子科技大学'
# 错误,p1没有school属性
# print(p1.school)
运行结果:
张三 is good good study,day day up!
注意:
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。
除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。