python的学习小记

1)关于with...as用的用法,这个主要是用于替换try...finally; 更多可以参见:理解Python中的with…as…语法

示例代码:

try:
    with open("foo.txt", "w+") as fo:
        fo.write("www.iptython.me");
    print(fo.closed);
except IOError as err:
    print("file error:\n" + str(err));
finally:

2)关于继承的,主要是用到了class关键字来建立,语法为 class derivedClass(baseClass): 在这个里面需要去实现__init__这个类似Java中的构造函数,相似的还有self,这个类似于this,但有一些在明确的就是,在python中,声明子类时,基类的__init__不会自动调用的,而且对于所有类的函数来说,self都要显示传入,而且也必须传入,因为如果用对象调用类的函数时,解析器会自动生成self,并将对象的引用赋给self,传入函数作为第一个参数。

示例代码:

#Finename: Inheritance.py
#Author: Kinthon

class SchoolMember:
    def __init__(self, name, age):
        self.name = name;
        self.age = age;
        print("init SchoolMember: ", self.name);
        return;

    def tell(self):
        print("name:%s; age:%s" %(self.name, self.age));
        return;

class Teacher(SchoolMember):
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age);
        self.salary = salary;
        print("init Teacher: ", self,name);
        return;

    def tell(self):
        SchoolMember.tell(self);
        print("Slary: ", self.salary);
        return;

class Student(SchoolMember):
    def __init__(self, name, age ,marks):
        SchoolMember.__init__(self, name, age);
        self.marks = marks;
        print("init Student: ", self.name);
        return;

    def tell(self):
        SchoolMember.tell(self);
        print("marks: ", self.marks);
        return;

#test:
t = Teacher('yangyang', 20, 1000);
s = Student('lili', 12, 86);
members = [t, s];

for member in members:
    member.tell();

 3)关于package,在python中package是一个分层次的文件目录结构,定义了由模块及子包和子包下的子包等组成的python应用环境,在package目录下需要有一个__init__文件,这个文件可以设置导入这个包的函数;参考:python模块

 

posted @ 2015-08-01 20:46  Kinthon  阅读(192)  评论(0编辑  收藏  举报