对象的绑定方法

时间:2020-02-01 12:30:14   收藏:0   阅读:87

对象的绑定方法

一、对象的绑定方法

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
stu1.func()
from func
stu2.func()
from func
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!