目錄python
class OldboyStudent: school = 'oldboy' 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')
類名稱空間中定義的數據屬性和函數屬性都是共享給全部對象用的函數
對象名稱空間中定義的只有數據屬性,並且是對象所獨有的數據屬性code
stu1 = OldboyStudent('nick', 18, 'male') stu2 = OldboyStudent('sean', 17, 'male') stu3 = OldboyStudent('tank', 19, 'female') print(stu1.name) print(stu1.school)
nick oldboy
print(OldboyStudent.choose_course)
<function OldboyStudent.choose_course at 0x10558e840>
try: OldboyStudent.choose_course(123) except Exception as e: print(e)
'int' object has no attribute 'name'
類中定義的函數是共享給全部對象的,對象也能夠使用,並且是綁定給對象用的,對象
綁定的效果:綁定給誰,就應該由誰來調用,誰來調用就會將誰看成第一個參數自動傳入it
print(id(stu1.choose_course)) print(id(stu2.choose_course)) print(id(stu3.choose_course)) print(id(OldboyStudent.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