python笔记之面向对象编程

看完天下足球和那该死的什么斯之旅,有种被骗的感觉,节目做的真是越来越步入俗套了,影响了心情,关掉电视开始反省自己。上一周虽然工作和生活日程还算丰富,内心却不免自责,自己的读书进度却是太慢,怎么说咱就要开始上班族2周年的庆祝了,此时却在技术领域上进步缓慢,唯有腰围和酒量大增。。。暂鉴定完毕,开始做笔记。

一、类的方法和对象调用
一般类中方法前初始的变量称为 类的变量,在类的方法中初始的变量为 对象的变量
定义方法时用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的例子,重抄了一遍,加了些注释

#!/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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值