心得:
面对难题你总是想着再拖后再学,你不去探索,你一直都会惧怕它.为什么不大胆的坚持一番,彻底做好自己的网页.今天写下关于我所理解的类,望自己有更高的进步.

类的用法
说实话我每次学到它,都很头疼,很抽象,不好理解,放慢一些,尝试着把类理解成一种实物,例如身边的手机,手机的功能有,电话,电视,音乐,聊天,拍照等,相当于把每一种独立的功能封装到手机里面,调用每一种功能,通过手机调用即可.来看一个实例吧.

class Iphone():
	def __init__(self,number,tv,music):
		self.number=number
		self.tv=tv
		self.__music=music
		self.time=1

	def call(self):
		print("call this number: %d" %self.number)

	def watch(self):
		print("I want to watch %s within %d hours" %(self.tv,self.time) )

	def listen(self,who):
		print("I want lesten to this \" %s \"  with %s" %(self.__music.title(),who))

my_iphone=Iphone(17521,"fairy story","take me to your heart")
my_iphone.call()
my_iphone.watch()
my_iphone.listen("xiaotudi")
print(my_iphone.tv) #未被私有化,可以访问并且修改tv这个参数,

注意点:

class Iphone():

创建类首字母一定是大写

def init(self,number,tv,music):

创建之后先进行初始化,或者一些形参的转移,init前后两个下划线,为什么会有一个self,你可以将self理解为我最后实例话的my_iphone,需要传入的形参,紧跟self.

self.number=number

为什么要做这个操作,这是将number这个形参引入整个类中,不用每次都去调用了

def listen(self,who):

如果一个类中除了开头定义的,还有方法中独立的参数,可以这样子去定义,和函数使用方法一致

my_iphone=Iphone(17521,“fairy story”,“take me to your heart”)

实例化类,将一个实例引入这个类,再加入参数,就可以使用类中全部的功能
来看看输出:

self.__music=music

设置私有变量,这个参数不可以被类之外的去访问,保护变量.

pythontianjain@tianjain-TM1701:~$ python3 0926.py 
call this number: 17521
I want to watch fairy story within 1 hours
I want lesten to this " Take Me To Your Heart "  with xiaotudi
fairy story

类的继承
类的继承,你可以将它想象成传宗接代,儿子继承了父亲的血液,比如眼睛和父亲一样,声音也一样,可嘴巴又不像,如果我们重新创建类的话,会占据大量的内存,我们可以去继承父亲已有的功能.来看一个实例吧.

class Android(Iphone):
	def __init__(self,number,tv,music,photo):
		super().__init__(number,tv,music)
		self.photo=photo

	def call(self):
		print("we are call \" %s \"" %self.number)
		
my_android=Android(110,"black story","marry you","hai")
my_android.call()
my_android.watch()
my_android.listen("xiaotudi")
print(my_android.photo)

class Android(Iphone):

继承你需要继承的类,并写入括号

def init(self,number,tv,music,photo):

初始化参数,如果全部调用父类的参数,则全部写入,如果有额外的参数,请之后添加

super().init(number,tv,music)

将父类和子类参数联系起来

def call(self):
print("we are call " %s “” %self.number)

重写方法,嫁入父类的方法你需要更新或者改进,则定义相同的名字,则再调用时会优先使用子类的方法
看一下输出:
we are call " 110 " #重新定义的方法
I want to watch black story within 1 hours #之前父类的方法
I want lesten to this " Marry You " with xiaotudi
hai #子类的变量

多继承

class Base(object):
    def play(self):
        print('Base is playing!')
 
        
class A(Base):  # 继承Base
	def __init__(self,name):
		self.name=name
	def play(self):
		print('%s is playing' %self.name)

class B(Base):  # 继承Base
	def __init__(self,age):
		self.age=age
	def played(self):
		print('B is playing and he age is : %d' %self.age)

class C(A, B):  # 继承A,B 
	def __init__(self,name,age):
		A.__init__(self,name)
		B.__init__(self,age)

 
c = C("tianjian",25)
c.play()
c.played()

输出:

tianjian is playing
B is playing and he age is : 25

如果类继承中存在参数需要继承可以使用以下两种方法:

  1. super().init(name)
    好处在于只继承一种类时,可以少写一个参数self
  2. A.init(self,name)
    当继承多个类时需要这样写,将父类的参数写入子类,并写入self