属性查找与绑定方法

class LuffyStudent:

school = 'luffycity'

def __init__(self,name,sex,age):
self.Name = name
self.Sex = sex
self.Age = age



def learn(self):
print('%s is learning'%self.Name)


def eat(self):
print('%s is eating'%self.Name)


def sleep(self):
print('%s is sleeping'%self.Name)


# 后产生对象
stu1 = LuffyStudent('王小丫', '女', 18)
stu2 = LuffyStudent('李三炮', '男', 38)
stu3 = LuffyStudent('张铁蛋', '男', 48)
print(stu1.__dict__)
print(stu2.__dict__)
print(stu3.__dict__)
...
{'Name': '王小丫', 'Sex': '女', 'Age': 18}
{'Name': '李三炮', 'Sex': '男', 'Age': 38}
{'Name': '张铁蛋', 'Sex': '男', 'Age': 48}
...
# 对象:特征与技能的结合体

# 类:类是一系列相似特征与相似的技能的结合体

# 类中的数据属性:是所有对象共有的
print(LuffyStudent.school, id(LuffyStudent.school))
print(stu1.school, id(stu1.school))
print(stu2.school, id(stu2.school))
print(stu3.school, id(stu3.school))
'''
luffycity 2297371606064
luffycity 2297371606064
luffycity 2297371606064
luffycity 2297371606064
'''
# 类中的函数属性:是绑定给对象使用的,绑定到不同的对象是不同的绑定方法,对象调用绑定方式时,会把对象本身当作第一个参数传入,传给self
print(LuffyStudent.learn)
print(stu1.learn)
print(stu2.learn)
print(stu3.learn)
'''
<function LuffyStudent.learn at 0x0000027AE6A79EA0>
<bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x0000027AE6A6AE80>>
<bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x0000027AE6A6AEB8>>
<bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x0000027AE6A6AEF0>>
'''
LuffyStudent.learn(stu1)
LuffyStudent.learn(stu2)
LuffyStudent.learn(stu3)
'''
王小丫 is learning
李三炮 is learning
张铁蛋 is learning
'''
原文地址:https://www.cnblogs.com/kingforn/p/11309071.html