Discuss / Python / 自己的一点小练习

自己的一点小练习

Topic source

类和对象,练习 class Student(object): def haha(self): print("haha") 创建实例练习 Stu1 = Student() Stu1.haha() 绑定属性练习 Student.age = 11 print(Student.age) 强制绑定属性练习 class Teacher(object): def init(self, name,age, subject): self.name = name self.age = age self.subject = subject 实例绑定任意属性练习 Jack = Teacher('Jack') //报错 John = Teacher('John', 20, 'math') Tim = Teacher('Tim' ,21, 'python') John.school = 'MIT' print(John.school) print(Tim.school)//报错:'Teacher' object has no attribute 'school'

小梦哒勒

#2 Created at ... [Delete] [Delete and Lock User]

你强制绑定属性school时,应该是 Teacher.school=' MIT'

楼上错了吧,不一定要Teacher.school,人家只是想给John添加school属性。

你只是给 Jonhn实例 绑定了 school 属性,而没给 Tim实例 绑定, print(Tim.school) Tim实例只能从Techer类中调用,而Teacher中也没有school属性 所以报错:'Teacher' object has no attribute 'school'

意思就是这样,表述的可能有点不准确。


  • 1

Reply