之前粗浅地学习过C++,对于面向对象有些了解,现在通过Python仔细学习一下面向对象:
类
类使用 class 关键字创建。类的域和方法被列在一个缩进块中。
class Person:pass #pass语句表示一个空类 p = Person() print(p)$ python simplestclass.py <__main__.Person object at 0x019F85F0>
#我们已经在 __main__ 模块中有了一个 Person 类的实例
对象的方法
class Person:def sayHi(self):#定义函数的时候有selfprint('Hello, how are you?')p = Person() p.sayHi() # This short example can also be written as Person().sayHi()
__init__方法
这个名称的开始和结尾都是双下划线
(感觉就像C++中的构造函数)
class Person:def __init__(self, name):self.name = namedef sayHi(self):print('Hello, my name is', self.name)p = Person('Swaroop')
一个对象创立时,该函数马上运行。
类和对象变量
就像C++中的静态变量和实例变量一样,很好理解,直接看这我写的简单的一个例子:
#Filename:claaOrInsVar class animal:population = 0def __init__(self,name):self.name = nameanimal.population += 1def sayHi(self):print("My name is " + self.name)def howMany ( ): #这个函数没有传递参数self# print('We have ' + animal.population + 'animals')#使用上面的代码后程序报错“ print('We have ' + animal.population + 'animals')#TypeError: must be str, not int”#animal.population 无法自动和字符串进行连接,java中是可以有表达式的自动提升的,python中却不能这样做print('We have {0} animals.'.format(animal.population)) an1 = animal('dogWW') an1.sayHi() an2 = animal('catMM') an2.sayHi() animal.howMany()
继承
class SchoolMenber:def __init__(self,name,age):self.name = nameself.age = agedef tell(self):print('name:{0} age:{1}'.format(self.name,self.age))class Teacher(SchoolMenber):def __init__(self,name,age,salary):SchoolMenber.__init__(self,name,age)#这里的self不要忘了写啊self.salary = salarydef tell(self):SchoolMenber.tell(self)print('salary: {0}'.format(self.salary))class Student(SchoolMenber):def __init__(self,name,age,mark):SchoolMenber.__init__(self,name,age)self.mark = markdef tell(self):SchoolMenber.tell(self)print('mark:{0}'.format(self.mark))stu = Student('Jenny',20,95) tec = Teacher('Mary',50,5000) menbers = [stu,tec] for menber in menbers:menber.tell()