一、类的方法和对象调用
一般类中方法前初始的变量称为 类的变量,在类的方法中初始的变量为 对象的变量
定义方法时用self变量作为类的默认属性,所有方法的其他变量(对象变量)赋值通过class.self传递为与类联系的链条。用户调用时通过 class.(对象变量的赋值).(方法)<除self默认外的参数>
按照A Byte of Python的例子再写一遍应该可以看懂每行的语句含义:
一般类中方法前初始的变量称为 类的变量,在类的方法中初始的变量为 对象的变量
定义方法时用self变量作为类的默认属性,所有方法的其他变量(对象变量)赋值通过class.self传递为与类联系的链条。用户调用时通过 class.(对象变量的赋值).(方法)<除self默认外的参数>
按照A Byte of Python的例子再写一遍应该可以看懂每行的语句含义:
- #!/usr/bin/python
- # -*- coding:gb2312 -*- #必须在第一行或者第二行
- #Filename:objvar.py
- class Person:
- '''''Represents a person'''
- population = 0 #初始化类变量
- def __init__(self,name):
- '''''Initializes the person's data'''
- self.name = name #定义__init__方法self.name域
- print 'Initializing %s' % self.name
- Person.population += 1
- def __del__(self): #不需要参数的方法仍要定义 self参数
- '''''I am dying'''
- print '%s says bye' % self.name
- Person.population -= 1
- if Person.population == 0:
- print 'I am the last one'
- else:
- print 'There are still %d people left.' % Person.population
- def sayHi(self):
- '''''Creating by the person.
- Really,that's all it does.'''
- print 'Hi,my name is %s' % self.name
- def howMany(self):
- '''''Prints the current population.'''
- if Person.population == 1:
- print 'I am the only one person here.'
- else:
- print 'We have %d person here.' % Person.population
- songy = Person('SongYang')
- songy.sayHi() # Person('SongYang').sayHi() SongYang实例的sayHi方法调用
- songy.howMany()
- swaroop = Person('Swaroop')
- swaroop.sayHi()
- swaroop.howMany()
- songy.sayHi()
- songy.howMany()
从上例也可看出,类的不同实例(对象)之间,都有自己在域上的不用拷贝,他们之间是不相通的。
二、继承
A Byte of Python的例子,重抄了一遍,加了些注释
二、继承
A Byte of Python的例子,重抄了一遍,加了些注释
- #!/usr/bin/python
- # -*- coding:gb2312 -*-
- # Filename: inherit.py
- class SchoolMember:
- '''''Represents any scholl member.'''
- def __init__(self,name,age): #定义SchoolMember类的2个参数
- self.name = name
- self.age = age
- print 'Initialized SchoolMember:%s' % self.name
- def tell(self):
- '''''Tell details.'''
- print 'Name:"%s",Age:"%s"' % (self.name,self.age), #别小瞧了末尾的这个逗号
- class Teacher(SchoolMember):
- '''''Represents a teacher.'''
- def __init__(self,name,age,salary): #Teacher类的3个属性
- SchoolMember.__init__(self,name,age) #从SchoolMember继承2个属性,终于知道原来这就是继承:)
- self.salary = salary #别忘了定义其他参数
- print 'Initialized Teacher:%s' % self.name
- def tell(self):
- SchoolMember.tell(self)
- print 'Salary:"%d"' % self.salary
- class Student(SchoolMember):
- '''''Represents a student.'''
- def __init__(self,name,age,marks):
- SchoolMember.__init__(self,name,age)
- self.marks= marks
- print 'Initialized Student:%s' % self.name
- def tell(self):
- SchoolMember.tell(self)
- print 'Marks:"%d"' % self.marks,
- t = Teacher('Mr.Swaroop',26,30000) # 类实例的三个属性
- s = Student('Song',22,77)
- members = [t,s]
- for member in members: #喜欢python当然也少不了对for...in的青睐
- member.tell()