Object OrientedObject Oriented
syntax of the class
-
To define a class:
Class Name:
Content
-
Example: Defining a person's class
#Defining ClassesclassPerson :#the embodiment of the act, by means? #Eat defEat (self):Print('Braised Chicken leg I like to eat')? #Play Basketball defPlay (self):Print('I like playing basketball')
- declaring objects
Bryant = Person ()
Bryant.eat ()
Bryant.play ()
- Set properties: Is dynamically added
Bryant.name = ' Kobe Bryant '
Print (Bryant.name)
?
-Grammar
?
-Defining a class requires the use of a keyword: class
-Class name: In principle, as long as it conforms to the naming conventions of identifiers, we usually use the big hump style (capitalize each word) to name
-Do not forget the colon after the class name ': '
-The contents of the class are indented
-Behavior: Through functions, similar to the way outside the definition of functions, the first parameter is self
-Properties: Represented by variables, properties are dynamically added, so they can be defined without
-Member Access:
-member properties: Object. Property name
-member Method: Object. Method Name ()
?
-Self
?
Example
?
"' Python
classPerson :defRun (self):#Self represents the current object: Who calls the method represents who Print('{} exercise 5km per day at 2m/s Speed'. Format (self.name))? defintroduce (self):#Self is a name that can be arbitrary, but it's all about this. #you can access both member properties Print('my name is {}'. Format (self.name))#You can also call member methodsSelf.run ()? Mugai=Person () Mugai.name='Wooden Lid'? #print (Mugai)Mugai.run ()? Curry=Person () Curry.name='Stephen, in the vault.'Curry.run ()#The calling method is the first parameter of self that does not needCurry.introduce ()
-
Description
-
Each member method has a parameter that does not need to be passed when it is called
-
The name may not be self, but usually we have to be self.
-
Self represents the current object, who calls the method to represent who, which object is called
-
You can access member properties through self, or you can call member methods
-
__ Str __ Method
class person: # # def __str__ # requires the return of a string return " my Name {}, this year {} " .format (Self.name, self.age) xiaoming = person ()
Xiaoming.name = " xiaoming Xiaoming.age = 18print (xiaoming)
Practice
-Customize a dog class, complete the dynamic addition of the property, call the method
-Properties: Name, age, color
-Method: Run, eat, swim, call
Python Object-oriented