zoukankan      html  css  js  c++  java
  • Python基础20-类的创建与删增改查

    1.用函数模拟类的创建

    #用函数模拟类的创建
    def chinese(name,age):
        def ini():
            dic = {
                    'name':name,
                    'age':age,
                     'eat':eat,
                    'sleep':sleep
                   }
            return  dic
        def eat(food):
            print('正在吃%s'%(food))
        def sleep():
            print('正在睡觉')
        return ini()
    print(chinese('alex','18')['eat'](''))

    2.类的创建

    class chinese:
        country = 'China'
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def eat(self,food):
            print('%s正在吃%s'%(self.name,food))
        def sleep(self):
            print('正在睡觉')
    p1 = chinese('alex','18')
    print(p1.name)
    p1.eat('')

    3.类属性的删增改查/类方法的增改

    class chinese:
        country = 'China'
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def eat(self,food):
            print('%s正在吃%s'%(self.name,food))
        def sleep(self):
            print('正在睡觉')
    p1 = chinese('alex','18')
    print(p1.name)
    p1.eat('')
    #查看类属性
    print(chinese.country)
    #修改类属性
    chinese.country = 'America'
    print(chinese.country)
    #删除类属性
    del chinese.country
    print(chinese.__dict__)
    #增加类属性
    chinese.country = 'China'
    chinese.location = 'Asia'
    print(dir(chinese))
    #类方法的增加
    def working():
        print('正在工作')
    chinese.working = working
    chinese.working()
    #修改类方法
    def test():
        print('测试')
    chinese.eat = test
    chinese.eat()

    4.通过实例修改属性只修改了实例的

    #通过实例修改属性只修改实例的
    class Chinese:
        country = 'China'
        def __init__(self,name):
            self.name = name
        def play_ball(self,ball):
            print('%s正在打%s'%(self.name,ball))
    p1 = Chinese('alex')
    print(p1.country)
    p1.country = '日本'
    print('类的--->',Chinese.country)
    print('实例的-->',p1.country)
  • 相关阅读:
    B1028人口普查
    B1004成绩排名
    B1041考试座位号
    A1009 Product of Polynomials多项式相乘
    A1002 A+B for Polynomials 多项式相加
    B1010一元多项式求导
    A1065 A+Band C(64 bit)
    A1046 Shortest Distance 最短路径
    排序
    windows 平台使用wireshark命令行抓包
  • 原文地址:https://www.cnblogs.com/josie930813/p/9883120.html
Copyright © 2011-2022 走看看