Python---动态添加属性以及方法

添加属性

class Person(object):
    def __init__(self, newName, newAge):
        self.name = newName
        self.age = newAge

p1 = Person("aa", 23)
p2 = Person("bb", 33)

# 1.对象添加属性
p1.addr = "深圳"

print p1.age,  p2.age       # 23   33
print p1.name, p2.name      # aa   bb
print p1.addr, p2.addr      # 深圳   报错:'Person' object has no attribute 'addr'

# 2.类添加属性
Person.num = 66
print p1.num,  p2.num       # 66   66

添加方法

import types
class Person(object):
    def __init__(self, newName, newAge):
        self.name = newName
        self.age = newAge

    def eat(self):
        print "---%s正在吃---" % self.name

def run(self):
    print "---%s正在跑---" % self.name

@staticmethod
def test():
    print "---static method---"

@classmethod
def nump(cls):
    print "---class method---"

p1 = Person("p1", 23)
p2 = Person("p2", 33)
p1.eat()      # ---p1正在吃---
p2.eat()      # ---p2正在吃---

# 1.添加对象方法
# 虽然p1对象中,run属性已经指向了run函数,但是不正确。因为run属性指向的函数,是后来添加的。在p1.run()的时候,并没有把p1当做第1个参数,导致函数调用的时候,出现缺少参数的问题。
# p1.run = run
# p1.run()
p1.run = types.MethodType(run, p1)
p1.run()      # ---p1正在跑---
p2.run()      # 报错:'Person' object has no attribute 'run'

# 2.添加静态方法
Person.test = test
Person.aaaa = test
Person.test()      # ---static method---
Person.aaaa()      # ---static method---

# 3.添加类方法
Person.nump = nump
Person.xxxx = nump
Person.nump()      # ---class method---
Person.xxxx()      # ---class method---

附加

# 规定类只能有哪些属性
class Person(object):
    __slots__ = ("age", "name")

p = Person()
p.age = 36
p.name = "p1"

# 规定对象只能有age和name属性,添加addr属性会报错
p.addr = "北京"

print p.age       # 36
print p.name      # p1
print p.addr      # 报错:'Person' object has no attribute 'addr'

猜你喜欢

转载自blog.csdn.net/qq_34802511/article/details/88810310