类的调用
实例化
class Luffy: school = 'luffy' def __init__(self,name,age): self.Name = name self.Age = age def learn(self): print('%s is learning' % self.Name) def eat(self): print('is eating') stu1 = Luffy('xing',19)
__init__,初始化方法,可差异化不同对象,self为自己本身,实例化时把 自己传递进去了
stu1 = Luffy('xing',19) print(stu1.Name)
Luffy.__init__(stu1,'yang',22) print(stu1.Name) --------------------------------------- xing yang
甚至可以通过以上方法更改属性
stu1 = Luffy('xing',19) stu1.learn() Luffy.learn(stu1) -------------------------------- xing is learning xing is learning
以上为调用类的方法的两种方法
注意:
实例化对象有自己的特有属性
stu1 = Luffy('Tom',19) stu2 = Luffy('Bob',22) print(stu1.__dict__) print(stu2.__dict__) --------------------------- {'Name': 'Tom', 'Age': 19} {'Name': 'Bob', 'Age': 22}
实例化对象的公共数据属性都指向类中数据属性的地址,而函数属性则是自己的地址
stu1 = Luffy('Tom',19) stu2 = Luffy('Bob',22) print(id(stu1.school)) print(id(stu2.school)) print(id(Luffy.school)) print(id(stu1.learn)) print(id(stu2.learn)) print(id(Luffy.learn)) ------------------------------- 15527680 15527680 15527680 # 数据属性地址一样 12010160 12010160 16096184 # 函数属性地址stu1和stu2一样(可能是Python新版的优化)
Python3 中统一了类型与类的概念
l1 = [1,2,3] l2 = list([4,5,6]) print(type(l1),type(l2)) l1.append(4) list.append(l2,7) print(l1) print(l2) ------------------ <class 'list'> <class 'list'> [1, 2, 3, 4] [4, 5, 6, 7]