Classes and methods
Name ="Jack" City="Bejing"Print("My name is%s and come from%s"%(name,city))Print("Hello 51zxw") name="Harry" City="Shengzhen"Print("My name is%s and come from%s"%(name,city))Print("Hello 51zxw"think about a few questions? What if there are 50 students in the class in turn? Classes and Objects Human properties: Geography, skin color, national functions: walking, thinking, eating, running specific objects: Chinese, african students attribute: name, school number, city, age function: Listening, reading, writing, speaking specific objects: Jack classmate, Harry classmate three special: encapsulation, inheritance, polymorphism define a student's class classStudent (object):#parentheses do not write default is also an object, can write not write def_init_ (self,name,city):#constructor FunctionSelf.name = Name#Self is the equivalent of a child who binds the name to the child.Self.city = CityPrint("My name is%s and come from%s% (name,city)")defTalk (self):Print("Hello 51zxw") to generate the instance object STU1= Student ("Jack","Beijing")#Creating ObjectsStu1.talk ()#Object Invocation MethodSTU2 = Student ("Harry", Shengzhen) Stu2.talk ()
Output Result:
Name is Jack and come from Beijing
Hello 51zxw
Example two:
class A (): def Add (self,a,b): return a+ = A ()print (count.add (3,5)) output:8
Example Three
class A (): def _init_ (self,a,b): = Int (a) = int (b) def Add (self): return self.a+ = A (3,4) count.add () Output:7 " " Parse: When the class A is called, the _init_ method is executed first, so it needs to be passed. The initialization is done by typing the input into the integer type, and add () can directly take the initialization of the SELF.A self.b to calculate, call Add () do not need to go through the parameter " " "
Inheritance of Classes
class A (): def add (self,a,b): return a+b Class B (A): def sub (self,a,b): return a-b print (B (). Add (3, 4)) # Call the parent class method output: 7print (B (). Sub (3, 4)) # Call your own method output: -1
A class was created, Class B was created, Class B inherits Class A, so B can call methods of Class A
Python classes and methods (object-oriented)