对象的概念同其他语言的对象相同
一个基本的类
-
#!/usr/bin/python class person: def hi(self,name): print 'Hello,%s'%name p1= person() p1.hi('lk')
[root@likun python_scripts]# python 12class.py Hello,lk
类的初始化:
当变量需要在类的多个函数中使用,要在class中假如初始化函数,函数的参数要在创建对象的时候加入
def __init__(self,name,salary): -- 定义
self.name1=name
p1= person('lk',20000) -- 调用
这时可以用 print p1.name1 ,self就是类本身,也就是创建的p1,因此可以p1直接调用所属变量
-
[root@likun python_scripts]# cat 12class.py #!/usr/bin/python class person: def __init__(self,name,salary): self.name=name self.salary=salary def hi(self): print 'Hello,%s'% self.name def hi2(self): print 'Yes,%s have %s every month!'%(self.name,self.salary) p1= person('lk',20000) p1.hi() p1.hi2()
[root@likun python_scripts]# python 12class.py Hello,lk Yes,lk have 20000 every month!
小练习:
建立一个狗的类(有名字和性别),它可以叫、吃饭、见到异性摇尾巴
-
[root@likun python_scripts]# cat 13dogclass.py #!/usr/bin/python class dog: def __init__(self,name1,sex1): self.name=name1 self.sex=sex1 def bark(self,default='low'): ifdefault=='low': print 'low..............' else: print 'hige.............' def eat(self,default='like'): ifdefault=='like': print 'good food,i like it!' else: print 'im full~ ~ ~ ~ ~ ~ ~' def tail(self,default): if self.sex !=default: print 'oh! shark~ ~ i like you~ ~' else: print 'hello ,you are my friend!' d1=dog('www','male') # 创建一个公狗 d2=dog('mmm','female') # 创建一个母狗 d1.bark() #狗叫 d1.eat() #吃饭 d1.tail('male') #d1见到一个公狗 d1.tail(d2.sex) #d1见到d2
-
[root@likun python_scripts]# python 13dogclass.py low.............. good food,i like it! hello ,you are my friend! oh! shark~ ~ i like you~ ~
真实使用中,不会在class程序文件中建立对象,在使用调用类时再创建对象:
-
>>>import dogclass >>> d1=dogclass.dog('www','male') >>> d2=dogclass.dog('mmm','female') >>> d1.bark() low.............. >>> d1.eat() good food,i like it! >>> d1.tail('male') hello ,you are my friend! >>> d1.tail(d2.sex) oh! shark~~~~ >>> d1.name 'www'
类的继承:
-
classPerson: #父类 def __init__(self,Type,Sex,Age,Name): self.race =Type self.sex =Sex self.age =Age self.name =Name def talk(self,msg=0): self.msg = msg if self.msg !=0: print self.name,'Saying:',self.msg class person_info(Person): #子类,括号里代表继承了谁 def __init__(self,Type,Sex,Age,Name,nation,work,salary): Person.__init__(self,Type,Sex,Age,Name) #调用父类的初始化方法 self.country = nation self.job = work self.salary = salary def tell(self,msg): return ''' %s's personal information: Name :%s Age :%s Nation:%s Work :%s ''' % (self.name,self.name,self.age,self.country,self.job)
b1=person_info('yellow','male','18','lk','china','it','20000')
b2=person_info('yellow','male','18','tom','china','it','20000')
g1=person_info('yellow','famale','18','jack','china','it','20000')
print '%s is looking for boyfriend: %s '%(g1.name,b1.tell('aaa'))
得到结果:
jack is looking for boyfriend: lk's personal information:
Name : lk
Age : 18
Nation: china
Work : it