• 类属性增删改查


    class Chinese:
       '''这是一个中国人的类'''
       def __init__(self, name, age, gender):
          self.mingzi = name
          self.nianji = age
          self.xingbie = gender
    
       def sui_di_tu_tan(self):
          print('%s竟然随地吐痰' % self.mingzi)
    
       def cha_dui(self):
          print('%s竟然随便插队' % self.mingzi)
    
       def eat_food(self, food):
          print('%s正在吃%s' % (self.mingzi, food))
    
    p1 = Chinese('alex', 18, 'boy')
    p1.sui_di_tu_tan()
    p1.cha_dui()
    p1.eat_food('蛋糕')
    
    
    class Chinese1:
       '''这也是一个中国人的类'''
       country = 'china'
       def __init__(self, name):
          self.name = name
    
       def play_ball(self, ball):
          print('%s正在打%s' % (self.name, ball))
    
    # 数据属性查看
    print(Chinese1.country)
    # 数据属性修改
    Chinese1.country = 'hongkong'
    print(Chinese1.country)
    p2 = Chinese1('alex')
    print(p2.country)
    # 数据属性增加
    Chinese1.dang = 'gongchandang'
    print(Chinese1.__dict__) # {'__module__': '__main__', '__doc__': '这也是一个中国人的类', 'country': 'hongkong', '__init__': <function Chinese1.__init__ at 0x000001C697BD8820>, 'play_ball': <function Chinese1.play_ball at 0x000001C697BD88B0>, '__dict__': <attribute '__dict__' of 'Chinese1' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese1' objects>, 'dang': 'gongchandang'}
    print(Chinese1.dang)
    print(p2.dang)
    # 数据属性删除
    del Chinese1.country
    print(Chinese1.__dict__) # {'__module__': '__main__', '__doc__': '这也是一个中国人的类', '__init__': <function Chinese1.__init__ at 0x000001C697BD8820>, 'play_ball': <function Chinese1.play_ball at 0x000001C697BD88B0>, '__dict__': <attribute '__dict__' of 'Chinese1' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese1' objects>, 'dang': 'gongchandang'}
    # 函数属性增加
    def eat_food(self, food):
       print('%s正在吃%s' % (self.name, food))
    Chinese1.eat = eat_food
    print(Chinese1.__dict__)
    p2.eat('包子')
    # 函数属性修改
    def test(self):
       print('test函数')
    Chinese1.play_ball = test
    Chinese1.play_ball(p2) # 函数属性名字没有修改,但是所执行的函数已经被更改(类调用函数属性仍需要传入参数)
    p2.play_ball() # 同上
    while True: print('studying...')
  • 相关阅读:
    Bootstrap 3的box-sizing样式导致UEditor控件的图片无法正常缩放
    Npm install failed with “cannot run in wd”
    JQuery使用deferreds串行多个ajax请求
    使用HTML5的History API
    Christmas Trees, Promises和Event Emitters
    Node.js开发者最常范的10个错误
    Mongoose Schemas定义中timestamps选项的妙用
    Ubuntu上安装Robomongo及添加到启动器
    [nodemon] Internal watch failed: watch ENOSPC错误解决办法
    介绍两个Ubuntu上的桌面小工具
  • 原文地址:https://www.cnblogs.com/xuewei95/p/14640797.html
Copyright © 2020-2023  润新知