python 学习笔记5

来源:互联网 发布:淘宝卖家主图视频教程 编辑:程序博客网 时间:2024/06/05 10:57

python learning notes 5

Module

Python has many useful modules preparing for us. e.g. sys

#!/usr/bin/env python3# -*- coding: utf-8 -*-' plain text '__author__='BetaCZH'import sys      #  import sys this moduledef test():    args=sys.argv    if(len(args)==1):        print('Hello world!')    elif(len(args)==2):        print('Hello,%s'%args[1])    else:        print('Too many arguments')if __name__=='__main__':    test()

Here, sys is a module. And this module has one argument by default: the name of this file. More arguments can be added through command line.

1.action sccope

This is also similiar to class attribute in c++. Through ‘’ or ‘_‘, we can mark this variable/function is private or public. This kind of method improves the quality of packaging.

2.Objected Oriented Programming(OOP)

In this secion, you will find class in python and in c++ are almost the same. Now let’s see an example:

#**********************#******  python  ******#**********************#!/usr/bin/env python3# -*- coding: utf-8 -*-class student(object):    def __init__(self,name,score):        self.name=name        self.score=score    def print_score(self):        print('%s:%s'%(self.name,self.score))student1=student('chen',98)student2=student('xia',100)student1.print_score()student2.print_score()
//*********************//******  c++   *******//*********************class student{    public:        student(string _name,int _score):name(_name),score(_score){};        ~student(){};        print_score(){cout<<name<<':'<<score<<endl;}    private:        string name;        int score;}

By comparasion, we can find that in python, you need to pass self(which is similiar to this in c++) to each member function. And you don’t need to declare variables in python separatedly.

3.class and instance

Just one thing to mention!!! In python, if you write a.__pic=’dog.png’, and you truly have an private variable named __pic, the statement above won’t modified __pic. On the contrary, it will add a new property to your object named __pic.(Actually, explainer has modified your private variable __pic to __Class__pic).

4.Inherit && polymorphim

Nothing to say. I don’t find any differece …

5.get information of objects.

python provides us with a couple of ways to visit information of object in a simple way:

  • type().
    return the type of the object.
  • isinstance().
    this func has been mentioned in the ealier blog. Return the judgement: True/False.
  • getattr(obj,’attr’,(returnValue)),setattr(…),hasatrr(…).
    These three functions give us a comprehensive way to access object and modify oject.
原创粉丝点击