• 如何使用类


    类在定义阶段已经能执行

    class luffystudent:
    school='luffycity'
    def learn(self):
    print('is learning')
    def eat(self):
    print('is eating')
    def sleep(self):
    print('is sleeping')

    》》》===run===

    查看类的名称空间,print(类名.__dict__)

    print(luffystudent.__dict__)

    {'__module__': '__main__', 'school': 'luffycity', 'learn': <function luffystudent.learn at 0x00000000021C97B8>, 'eat': <function luffystudent.eat at 0x00000000021C9840>, 'sleep': <function luffystudent.sleep at 0x00000000021C98C8>, '__dict__': <attribute '__dict__' of 'luffystudent' objects>, '__weakref__': <attribute '__weakref__' of 'luffystudent' objects>, '__doc__': None}

    类的增删改查:

    #查
    #print(luffystudent.school)
    #print(luffystudent.learn)

    #增
    print(luffystudent.__dict__['school'])
    luffystudent.county='china'
    print(luffystudent.__dict__)

    #删
    # del luffystudent.county
    # print(luffystudent.__dict__)

    #改
    luffystudent.school='LuffyCity'
    print(luffystudent.__dict__)

    类内部定义的变量是类的数据属性

        类的数据属性是每个实例化的对象共有的,通用的

    类内部定义的函数是类的函数属性

         类的函数属性是每个实例化的对象私有的,谁调用就是谁的

    举个栗子

    class luffystudent:
    def __init__(self,name,sex,age):
    self.name=name
    self.sex=sex
    self.age=age
    school='luffycity'
    def learn(self,x):
    print('%s is learning %s' %(self.name,x))
    def eat(self):
    print('is eating')
    def sleep(self):
    stu1=luffystudent('sunny','nan','28')
    stu2=luffystudent('alex','男','30')
    stu3=luffystudent('egon','nan','31')

    返回:

    luffycity 30850608
    luffycity 30850608
    luffycity 30850608

    对象调用函数:

    stu1.learn(1)
    luffystudent.learn(stu1,1)

    stu2.learn(2)
    luffystudent.learn(stu1,1)

    返回:

    sunny is learning 1
    sunny is learning 1

    alex is learning 2
    alex is learning 2








    如何使用类
    #定义类
    class luffystudent:
    def __init__(self,name,sex,age):
    self.name=name
    self.sex=sex
    self.age=age


    school='luffycity'
    def learn(self):
    print('is learning')
    def eat(self):
    print('is eating')
    def sleep(self):
    print('is sleeping')


    #后产生对象
    stu1=luffystudent('sunny','nan','28')
    #实例化步骤
    #1.创建一个空对象
    #2.luffystudent.__init__(stu1,'sunny','nan','28')


    # print(luffystudent.__init__)
    # print(stu1.__dict__)
    # print(stu1.name)

    sty2=luffystudent('alex','nan',35)
    print(sty2.__dict__) #sty2名称空间,键是属性名,值为属性值
  • 相关阅读:
    团队冲刺(九)
    团队冲刺(八)
    团队冲刺(七)
    团队冲刺(六)
    团队冲刺(五)
    背景图片-密度屏幕(移动端)
    响应字体大小(移动端)
    FLEX 布局
    图片垂直居中
    css reset
  • 原文地址:https://www.cnblogs.com/sunny666/p/9629554.html
Copyright © 2020-2023  润新知