linux下python学习笔记(十六)

来源:互联网 发布:学生平板电脑推荐知乎 编辑:程序博客网 时间:2024/05/01 01:40

#!/usr/bin/python
# Filename: objvar.py
class Person:
  '''Represents a person.'''
  population = 0
  def __init__(self, name):
    '''Initializes the person's data.'''
    self.name = name
    print '(Initializing %s)' % self.name
    # When this person is created, he/she
    # adds to the population
    Person.population += 1
 def __del__(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):
    '''Greeting 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 person here.'
    else:
       print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()

记住,你只能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考 。

只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。
这样就有一个惯例,如果某个变量只想在类或对象中使用,就应该以单下划线前缀。而其他的名称都将作为公共的,可以被其他类/对象使用。记住这只是一个惯例,并不是Python所要求的(与双下划线前缀不同)。

继承

面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过 继承 机制。

#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
  '''Represents any school member.'''
  def __init__(self, name, age):
    self.name = name
    self.age = age
    print '(Initialized SchoolMember: %s)' % self.name
  def tell(self):
    '''Tell my details.'''
    print 'Name:"%s" Age:"%s"' % (self.name, self.age),
class Teacher(SchoolMember):
  '''Represents a teacher.'''
  def __init__(self, name, age, salary):
     SchoolMember.__init__(self, name, age)
     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('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
   member.tell() # works for both Teachers and Students

  Python不会自动调用基本类的constructor,你得亲自专门调用它。

 

 

 

 

 

 

 

原创粉丝点击