python添加属性的方式有,直接在对象上面添加属性:
1.挂载属性:
例如:
>>> class Person(object):
def __init__(self, name = None, age = None): self.name = name self.age = age >>> P = Person("小明", "24")
P.sex = "male"#动态的添加了sex属性,但是新建的对象不会拥有这个属性
如果这样写Person.sex = None,新建的都会有这个属性。
2.挂载方法:
通过import types
实现对对象动态添加方法。
#定义一个类方法
@classmethod
def testClass(cls): cls.num = 100 #定义一个静态方法 @staticmethod def testStatic(): print("---static method----")
#给Person类绑定类方法
Person.testClass = testClass
#给Person类绑定静态方法
Person.testStatic = testStati
删除的方法:
- del 对象.属性名
- delattr(对象, "属性名")