#!/usr/bin/env python #-*-coding:utf-8-*-' class Define ' __author__ = ' Hui.qian ' 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) Bart = Student (' Hui.qian ', m) Lisa = Student (' Zuomu.qian ', M) Bart.print_score () Lisa.print_score () class Student1 (object): Pass Qian = Student1 () print Qian qian.name = ' hui ' Print qian.name ' access
Limit ' #在变量前加2个下划线, the variable becomes private class Student2 (object): Def __init__ (self,name,score): Self.__name = Name
Self.__score = Score def print_score (self): print '%s:%s '% (self.__name,self.__score) def get_name (self): Return Self.__name def get_score (self): return Self.__score hui = Student2 (' Hui.qian ', ', ') hui.print_ Score () print hui.get_name () print hui.get_score () ' Inheritance and Polymorphism ' class Father (object): Def call_father (self): p Rint ' Daddy ' class Son (Father): Def print_name (self): print ' I\ ' m your son ' def call_father (self): print ' Daddy: ' Class Daughte
R (Father): def print_name (self): print ' I\ ' m your Daughter ' Def Call_father (self): print ' daddy! ' son = Son () son.call_father () son.print_name () daughter = Daughter () Daughter.call_father () daughter.print_name () print Isinstance (son,father) print isinstance (daughter,father) ' Get object Info ' #type () to determine the object type print type (' 123 ') print type (123) print Type (son) print type ([1,2,3]) Print type ((1,2)) print type ({1:2,2:3,3:4}) print type (set ([1,2,3]) #type模块 import types P Rint type (' 123 ') = = types. StringType Print type (123) ==types. Inttype Print type (U ' 123 ') ==types. Unicodetype print type ([]) = = types. ListType print Type (str) ==types. Typetype print type (int) ==type (str) ==types. Typetype #isinstance () #之前用过, do not repeat print isinstance (' A ', (Str,unicode)) #basestring是str和unicode的父类 print isinstance (' Ad ', basestring ' gets all properties and methods of the object ' #dir print dir (list) #操作属性: Hasattr,setattr,geattr Print hasattr (Lisa, ' name ') print Lisa.name setattr (Lisa, ' name ', ' Xiaohui ') print getattr (Lisa, ' name ') print GetAttr (Lisa, ' names ', 404) Print Hasattr (Lisa, ' score ') #操作方法 print hasattr (Lisa, ' Print_score ') F = getattr (Lisa, ' Print_
Score ') F ()