- # 定义一个 Python 类
- class Cat:
- #self 关键字相当于 c++ 类中的 this 指针
- def eat(self):
- print("i am eating .")
- def show(self):
- print("name is %s"%self.name);
- tom = Cat()
- tom.eat()
- # 为 tom 对象添加一个属性
- tom.name = "tom"
- tom.show() #执行成功
- print("------------");
- lanmao = Cat()
- lanmao.show() #执行失败 错误信息: AttributeError: 'Cat' object has no attribute 'name'
- '''
- 注意
- pyhthon 中 class 关键字定义的类并非 C++ 意义上的类, python 的类更加类似于一个模板,
- 通过该 python 类生成的对象可以随意修改的属性, 同一个 python 创建的对象不一定拥有相同的属性,
- 导致 Python 中的一些方法需要特别注意, 不要随意在类的方法中使用对象的属性, 因为不一定每个对象都拥有这些属性
- '''
来源: http://www.bubuko.com/infodetail-2741656.html