• 对象的绑定方法


    对象的绑定方法

    一、对象的绑定方法

    class Student:
        school = 'hnnu'
    
        def __init__(self, name, age, gender):
            self.name = name
            self.age = age
            self.sex = gender
    
        def choose_course(self):
            print(f'{self.name} choosing course')
    
        def func(self):
            print('from func')
    
    • 类名称空间中定义的数据属性和函数属性都是共享给所有对象用的
    • 对象名称空间中定义的只有数据属性,而且是对象所独有的数据属性

    二、类使用对象的绑定对象

    stu1 = Student('randy', 18, 'male')
    stu2 = Student('sun', 17, 'male')
    stu3 = Student('laowang', 19, 'female')
    
    print(stu1.name)
    print(stu1.school)
    randy
    hnnu
    
    • 类中定义的函数是类的函数属性,类可以使用,但使用的就是一个普通的函数而已,意味着需要完全遵循函数的参数规则,该传几个值就传几个
    print(Student.choose_course)
    <function Student.choose_course at 0x10558e840>
    try:
        Student.choose_course(123)
    except Exception as e:
        print(e)
    'int' object has no attribute 'name'
    

    三、对象使用对象的绑定方法

    • 类中定义的函数是共享给所有对象的,对象也可以使用,而且是绑定给对象用的,
    • 绑定的效果:绑定给谁,就应该由谁来调用,谁来调用就会将谁当作第一个参数自动传入
    print(id(stu1.choose_course))
    print(id(stu2.choose_course))
    print(id(stu3.choose_course))
    print(id(Student.choose_course))
    4379911304
    4379911304
    4379911304
    4384680000
    print(id(stu1.school))
    print(id(stu2.school))
    print(id(stu3.school))
    4380883688
    4380883688
    4380883688
    print(id(stu1.name), id(stu2.name), id(stu3.name))
    4384509600 4384506072 4384507864
    stu1.choose_course()
    nick choosing course
    stu2.choose_course()
    sean choosing course
    stu3.choose_course()
    tank choosing course
    
    • 补充:类中定义的函数,类确实可以使用,但其实类定义的函数大多情况下都是绑定给对象用的,所以在类中定义的函数都应该自带一个参数self
    stu1.func()
    from func
    stu2.func()
    from func
    
    在当下的阶段,必将由程序员来主导,甚至比以往更甚。
  • 相关阅读:
    [包计划] date-fns
    [包计划] create-react-app
    [包计划] js-cookie
    [包计划] cheerio
    [包计划] 30-seconds-of-code
    new
    [源计划] array-first
    [源计划] is-sorted
    [源计划] array-flatten
    images
  • 原文地址:https://www.cnblogs.com/randysun/p/12248008.html
Copyright © 2020-2023  润新知