python-基础笔记4-面向对象

来源:互联网 发布:c语言delay头文件 编辑:程序博客网 时间:2024/06/05 02:49
面向对象最主要的是(类和继承)类:用来描述相同属性和方法的集合
class Employee:    '''    python多行注释,在import引入类之后,可以用help(className)来查看类的方法和属性,这段注释就是该类的说明,会一起显示。    this is a test demo class    '''    classtr="itis a test class"    def __init__(self, name, pay):        self.name=name        self.pay=pay    def hello(self):        '''        say hello        '''        print self.name        print "say hello"# python json.py# python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import json   #使用类就引入类,python类相当于python的一个模块>>> worker = json.Employee('xiaoming', 10000)>>> type(worker)<type 'instance'>>>> worker.hello<bound method Employee.hello of <json.Employee instance at 0x7f34422f82d8>>>>> worker.hello()xiaomingsay hello>>> worker2=json.Employee('zhangqiaong',2)>>> worker2.hello()zhangqiaongsay hello>>> help(json.Employee)>>> help(worker2)

python内置类属性

__dict__  类的属性(包含一个字典,由类的数据属性组成)__doc__   类的文档字符串__name__  类名__moudle__ 类定义所在的模块(类的全名是'__main__className',如果类位于一个导入模块mymod中,那么'className__moudle__' 等于 mymod)__bases__  类的所有父类构成元素
类的继承:
class Parent:    parentAttr=100    def __init__(self):        print "调用父类构造方法"    def parentMethod(self):        print "调用父类方法"    def setAttr(self, attr):        Parent.parentAttr = attr    def getAttr(self):        print  '父类属性:', Parent.parentAttrclass Child(Parent):  #继承父类    def __init__(self):        print "调用子类构造方法"    def childMethod(self):        print '调用子类方法 child method'>>> import json>>> from json import Parent,Child>>> p1=Parent()调用父类构造方法>>> p1.parentMethod()调用父类方法>>> p1.getAttr()父类属性: 100>>> p1.setAttr(200)>>> p1.getAttr()父类属性: 200>>> p2=Child()调用子类构造方法>>> p2.childMethod()调用子类方法 child method>>> p2.parentMethod()调用父类方法>>> p2.getAttr()父类属性: 200class Child(Parent):  #定义子类    def __init__(self):        Parent()         #调用父类的构造方法        print "调用子类构造方法"    def childMethod(self):        print '调用子类方法 child method'>>> from json import Parent, Child>>> p2=Child()调用父类构造方法调用子类构造方法

类的私有属性不能在类外部访问或直接使用

__private_attr class Parent:   #定义父类    parentAttr=100    __six = 'man'  #定义私有属性    def __init__(self):        print "调用父类构造方法"    def showsix(self):        print self.__six
from json import*   #导出json文件包的所有类(一个文件包含多个类)
globals() 打印全局变量locals() 打印局部变量