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.
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.
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.
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).
Nothing to say. I don’t find any differece …
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.