- 对象属性添加有两种办法:
a. 直接赋值,语法p1.address=‘值’
b. 使用setattr(对象名,属性名,值) 【set 设置的意思 Attribute属性的意思】 - 类属性添加
类名.属性名=值 当在类上添加了属性并赋值后,在两个对象上都起作用了
class Person():
def __init__(self, name,age):
self.name=name
self.age=age
p1=Person('张明',19)
# 1、给对象添加一个属性
p1.address='河南'
print('姓名:%s ,年龄%d,地址:%s' % (p1.name,p1.age,p1.address))
# 给使用setattr添加一个属性
setattr(p1,'gender','男')
print('姓名:%s ,年龄:%s,地址%s,性别%s' % (p1.name,p1.age,p1.address,p1.gender))
# 再实例化一个对象
p2=Person('小李',22)
# 添加的属性在另一个对象中不起做用,运行报错AttributeError: 'tuple' object has no attribute 'gender'
# print(p2.gender)
# 2、添加类属性
Person.classId=3001
# 给类属性添加时必须赋值,在对象处赋值不能用
# Person.width
print(Person.classId)
# 添加完类属性,在两个对象上都起作用
print(p1.classId)
print(p2.classId)
# 不可以在对象这里赋值,报属性错误
# p1.width=68
# print(p1.width)
添加方法
- 对象添加方法
先引入types 通过 import types引用
语法:对象名.方法名 types.MethodType(方法名,对象名)
添加后只能是添加的对象可调用 - 添加静态方法
@staticmethod
类名.静态方法名=定义的函数名 - 添加类方法
@classmethod
类名.类方法名=定义的函数名 注意:这个函数名要有cls参数
import types
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def study(self):
print('这是一个学生方法,这个学生是%s 年龄是%s' % (self.name, self.age))
p1 = Person('刘同学', 22)
p2 = Person('张同学', 36)
# 向对象中添加一个方法,通过types。MethodType把方法和对象进行绑定
p1.study = types.MethodType(study, p1)
# 执行绑定好的方法,一切顺利
p1.study()
# 没有对P2这个对象绑定方法,所以如果执行p2的这个方法报错
# p2.study()
# 添加静态方法
@staticmethod
def testStaticMethod():
print('这是个静态方法')
# 把上面的进态方法和类绑定
Person.method1 = testStaticMethod
# 调用这个绑定的静态方法
Person.method1()
# 当把静态方法绑定给类以后,两个对象上也有这个方法了,下面两行输出正常
p1.method1()
p2.method1()
# 添加类方法
@classmethod
def testClassMethod(cls):
print('这是我加进去的一个类方法')
# 绑定方式和绑定静态方法一样
Person.class_method = testClassMethod
# 这时候检测类和对象执行这个绑定的方法
Person.class_method()
# 对象执行这个方法
p1.class_method()
p2.class_method()
# 总结:需要注意的是在绑定类法方的时个用了装饰器,另外类方法绑定时方法要带参数cls
限定属性添加slots
- 使用slots限定对象添加属性
- 但继承的对象不受影响
- 也不影响类添加属性
【slots插槽的意思】
import types
class Person():
__slots__ = ('name', 'age')
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print('开始吃饭')
class Student(Person):
pass
def jump():
print('这是要添加的方法')
p1 = Person('小李', 22)
# 限定对象添加类后提示AttributeError: 'Person' object has no attribute 'gender'
# p1.gender='男'
# slots变不限定类添加属性,类的属性可以正常显示
Person.cls_id = 110
print(Person.cls_id)
# 方法也不能被正常添加AttributeError: 'Person' object has no attribute 'jump'
# p1.jump=types.MethodType(jump,p1)
# p1.jump()
# 子类添加属性测试,子类不受slots的限制
s1 = Student('小王', 22)
s1.gender = '男'
print(s1.gender)