Python 类的初见

#定义一个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中的一些方法需要特别注意,不要随意在类的方法中使用对象的属性,因为不一定每个对象都拥有这些属性
'''
原文地址:https://www.cnblogs.com/zhanggaofeng/p/9533113.html