Python 类

类,对象,实例化
class Person(object):
def __init__(self,name,age):
self.name=name
self.age= age
def run(self):
print ("Runing %s"%(self.name))
def speak(self,msg):
print ('%s:%s'%(self.name,msg))

a=Person('jim',22)
b=Person('freeman',23)
a.run()
b.run()
print ("---------------")
a.speak('hello')
b.speak('sb')
#############################################################
class Cat(object):
def __init__(self,name,color):
self.name=name
self.color=color
def run(self):
print ('run %s'%(self.name))
def cry(self):
print ('miao miao miao.....')
def catch_mouse(self):
print ('the catch mouse...')
class Dog(object):
def __init__(self,name,color):
self.name=name
self.color=color
def run(self,name):
print ('running %s'%(self.name))
def eat(self,eatfood):
print ('%s now is eat'%(self.name,eatfood))
def cry(self):
print ('bark bark')
def swim(self):
print ('The Doe swimming')
def __del__(self):
print ('Done')
class Elephant(object):
def __init__(self,name,color):
self.name=name
self.color=color
def cry(self):
print ("The elephant is shouting...")
def spary_water(self):
print ('The elephant is spraying water....')
import cat
import dog
import elephant

class Pet(object):
def __init__(self,pet):
self.pet=pet
def pet_cry(self):
self.pet.cry()

#pet= elephant.Elephant('alex','heise')
pet = dog.Dog("fe",'black')
#pet = cat.Cat('mao','color')
My_pet =Pet(pet)
My_pet.pet_cry()
###################################
抽象类
from abc import ABCMeta , abstractmethod
class h1(object):
__metaclass__ = ABCMeta
def __init__(self,a,b):
self.a=a
self.b=b

@abstractmethod
def start(self):
pass
@abstractmethod
def end(self):
pass
@abstractmethod
def abc(self):
print ('abc')

from h1 import h1
class h2(h1):
def __init__(self,a,b):
h1.__init__(self,a,b)
self.name=a
def start(self):
print ('start %s'%(self.name))
def end(self):
print ( 'End')

a=h2('FM','sam')
a.start()
a.end()
print (a.name)
##############################################
类的继承
#from abc import ABCMeat, abstractclassmethod

class Car(object):
def __init__(self,color,brand):
self.color=color
self.brand=brand
def run(self):
print ('The car is running')
def info(self):
print ("Thar car info %s %s"%(self.color,self.brand))
'''
class Car1(object):
__metaclass__ = ABCMeat
@abstractclassmethod
def start(self):
pass

'''
from car import Car
class Bmw(Car):
def __init__(self,color,brand,a):
Car.__init__(self,color,brand)
self.a=a
self.color=color

def start(self):
print ('BMW STARTING %s %s'%(self.a,self.color))
b=Bmw('bmw','bmw123','a')
b.run()
b.info()
b.start()
########################
静态类写法
class Tools(object):
#@classmethod
@staticmethod
#def encrypt(cls,data):
def encrypt(data):
print ("Encrypt data....%s"%(data))

#Tools.encrypt(Tools,"Love You")
Tools.encrypt('haha')
###############

posted @ 2016-04-12 19:11  FreeMan1  阅读(250)  评论(0编辑  收藏  举报