首页 > 代码库 > 一入python深似海--class

一入python深似海--class

python class

分为三个部分:class and object(类与对象),inheritance(继承),overload(重载)and override(覆写)。

class and object

类的定义,实例化,及成员访问,顺便提一下python中类均继承于一个叫object的类。
class Song(object):#definition

    def __init__(self, lyrics):
        self.lyrics = lyrics#add attribution

    def sing_me_a_song(self):#methods
        for line in self.lyrics:
            print line

happy_bday = Song(["Happy birthday to you",
                   "I don't want to get sued",
                   "So I'll stop right there"])#object1

bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])#object2

happy_bday.sing_me_a_song()#call function

bulls_on_parade.sing_me_a_song()

inheritance(继承)

python支持继承,与多继承,但是一般不建议用多继承,因为不安全哦!
class Parent(object):

    def implicit(self):
        print "PARENT implicit()"

class Child(Parent):
    pass

dad = Parent()
son = Child()

dad.implicit()
son.implicit()

overload(重载)and override(覆写)

重载(overload)和覆盖(override),在C++,Java,C#等静态类型语言类型语言中,这两个概念同时存在。
python虽然是动态类型语言,但也支持重载和覆盖。

但是与C++不同的是,python通过参数默认值来实现函数重载的重要方法。下面将先介绍一个C++中的重载例子,再给出对应的python实现,可以体会一下。

C++函数重载例子:
void f(string str)//输出字符串str  1次
{
      cout<<str<<endl;
}
void f(string str,int times)//输出字符串  times次
{
      for(int i=0;i<times;i++)
       {
            cout<<str<<endl;
        }
}

python实现:

通过参数默认值实现重载
<span style="font-size:18px;">def f(str,times=1):
       print str*times
f('sssss')
f('sssss',10)</span>


覆写

class Parent(object):

    def override(self):
        print "PARENT override()"

class Child(Parent):

    def override(self):
        print "CHILD override()"

dad = Parent()
son = Child()

dad.override()
son.override()

super()函数

函数被覆写后,如何调用父类的函数呢?
class Parent(object):

    def altered(self):
        print "PARENT altered()"

class Child(Parent):

    def altered(self):
        print "CHILD, BEFORE PARENT altered()"
        super(Child, self).altered()
        print "CHILD, AFTER PARENT altered()"

dad = Parent()
son = Child()

dad.altered()
son.altered()

python中,子类自动调用父类_init_()函数吗?

答案是否定的,子类需要通过super()函数调用父类的_init_()函数

class Child(Parent):

    def __init__(self, stuff):
        self.stuff = stuff
        super(Child, self).__init__()