python 学习笔记5

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 module

def 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值