20171106类的定义、继承、重写、私有变量

 

 

类的定义:

class <类名>:
 <语句>

 

#!/usr/bin/env python

class People(object):               # 定义类,object 是超级类,所有的类都必须继承这个类
    color = 'yellow'                # 定义类的属性
    def hello(self):                # 定义类的方法(self表示类本身)
        print "hello word"

ren = People()                      # 通过类实例化出一个对象ren
print ren.color                     # 可以通过对象访问类的属性
ren.hello()                         # 可以通过对象执行类的方法

__init__  构造函数,在生成对象时调用,当实例化一个对象时,自动执行 __init__ 下面的属性和方法:

class ren(object):
    name = 'xyt'
    def __init__(self):
        self.name = 'AAA'
        print "hao ren!"

a = ren()
print ren.name              //用类调用的时候name属性为xyt
print a.name                //用实例化的对象调用的name属性就换了

out:
hao ren!
xyt
AAA

 

类的继承:

继承是相对两个类而言的父子关系,子类继承了父类的所有公有属性和方法,继承可以重用已经存在的方法和属性,减少代码的重复编写,Python 在类名后使用一对括号来表示继承关系,括号中的类即为父类,如 class Myclass(ParentClass) 表示 Myclass(子类) 继承了 ParentClass(父类) 的方法和属性

#!/usr/bin/python

class People(object):     
    color = 'yellow'

    def think(self):
        print "I am a thinker"

class Chinese(People):    # 这里表示 Chinese 继承了 People
    pass

cn = Chinese()            # 因为 Chinese 继承了 People ,所以可以直接调用 People 里面的属性和方法
print cn.color
cn.think()

#如果父类定义了 __init__ 方法,子类必须显式调用父类的 __init__ 方法:

#!/usr/bin/python

class People(object):
    color = 'yellow'

    def __init__(self, c):
        print "Init...."

    def think(self):
        print "I am a thinker"

class Chinese(People):    
    def __init__(self):
        People.__init__(self,'red')    # 显式调用父类的__init__方法

cn = Chinese()

 类的重写:

class A :
    def hello(self):
        print('Hello,i am A.')
class B(A):
    def hello(self):
        print('Hello,i am B.')

 如果需要用父类的方法,并需要添加内容

class A :
    def hello(self):
        print('Hello,i am A.')
class B(A):
    def hello(self):
        super(B,self).hello()
        print('Hello,i am B.')

类的私有变量就是再变量前面加两条下划线,实例化的对象是不能访问私有变量,但是可以通过定义方法调用私有变量

 

posted @ 2017-11-07 09:26  木头爱木头媳妇  阅读(89)  评论(0)    收藏  举报