Python study NOTE 2: Class Definition and inheritance
# Class definition
Format:
Class Name (parent class ):
_ Init (self, parameter)
Member Method
Member variables
# Basic object of all classes
# Start With _ for private methods and variables
For example, define a bird
Class Bird (object): _ have_feather = True # private attribute: whether the feather way_of_reproduct = "egg" # public attribute: reproduction mode def move (self, dx, dy ): # public method position = [0, 0] position [0] = position [0] + dx position [1] = position [1] + dy return position
Define a chicken class: inherited from birds
Class Chicken (Bird): way_of_move = "walk" # Add a public attribute
Define a seagull class: inherited from birds
Class Oriole (Bird): way_of_move = "fly" # Add a public attribute
Define a Happy bird: inherited from birds
Class happyBird (Bird): def _ init (self, words): # constructor print "We are happy birds,", words
Usage:
summer = Bird()print "after move:",summer.move(5,8)happy = happyBird()
Example: define a human
Class Human (object): laugh = "hahaha" # public attribute def _ init _ (self, gender): # constructor self. gender = gender # define and initialize the public attribute def _ show_laugh (self): # private method print self. laugh def show_laugh_twice (self): # public method self. show_laugh () # Call the private method self. show_laugh () # Call a private Method
Usage:
man = Human("male")man.show_laugh_twice()print man.gender
Appendix:
# Built-in functions
# Dir () is used to query the attributes of a class or object.
# Help () for instructions
# Common sequence Functions
Len (s)-number of elements
Min (s)-minimum element
Max (s)-maximum element
Sum (s)-sum
S. count (x)-number of occurrences of element x in sequence s
S. index (x)-subscript of the first occurrence of element x in series s
# TABLE (the element division of the value table cannot be changed)
L. extend (l2)-add all l2 elements after table l
L. append (x)-add an x element to the end of l
L. sort ()-sort the elements in l
L. reverse ()-reverse order of elements in l
L. pop ()-return: the last element of table l, and delete this element from table l.
Del l [I]-delete this element