zoukankan      html  css  js  c++  java
  • python 给对象添加方法

    import types
    class Person:
        def __init__(self,name):
            self.name=name
        def eat(self):
            print('{}正在吃....'.format(self.name))
    def run(self):
        print('{}正在跑'.format(self.name))
    
    p=Person('小明')
    p.eat()
    #给对象添加方法
    p.run=types.MethodType(run,p)  #将p当成参数传给run函数,然后赋值给p.run
    
    p.run()
    print(p.__dict__)
    
    print(type(p.eat))
    print(type(p.run))
    
    小明正在吃....
    小明正在跑
    {'name': '小明', 'run': <bound method run of <__main__.Person object at 0x00000256B8D942B0>>}
    <class 'method'>
    <class 'method'>
    写出漂亮的博客就是为了以后看着更方便的。
  • 相关阅读:
    HDU 6043
    HDU 6033
    HDU 6041
    HDU 6050
    HDU 6053
    HDU 6055
    HDU 6045
    HDU 6044
    HDU 6040
    ZUFE 1035 字符宽度编码(字符串)
  • 原文地址:https://www.cnblogs.com/zhaowei5/p/10251157.html
Copyright © 2011-2022 走看看