python: Classes and Objects

Create a class

+ class + class name: back to indent, the class name first letter capitalized

 

 

 Examples

. 1  class Chinese:       # Create a class 
2      Eye = ' Black ' 
. 3  
. 4      DEF EAT (Self):
 . 5          Print ( ' eat, selected with chopsticks. ' )
 . 6  
. 7 Wufeng = Chinese ()    # class instantiation 
. 8  Print (Wufeng .eye)    # instance calls the class attributes 
. 9 wufeng.eat ()   # method call class (no reference transfer tube self)

Class is created and calls

 

 

 Two key points to create a class: self and initialization method (constructor)

self:

1. As long as the class with def create methods, we must take the first argument position left to self , and ignore it when calling the method (not to self parameter passing).

2. When the method of internal class want to call class properties or other methods should be employed self. Attribute names or self. Format method name.

Initialization method (constructor)

Format definition initialization process is DEF the __init __ (Self) , by init plus left and right sides of the underscore] bis [( the initialize abbreviation "initialization").

 

. 1  class Chinese:
 2  
. 3      DEF  the __init__ (Self, name, Birth, Region):
 . 4          the self.name name =    # the self.name = 'Feng Wu' 
. 5          self.birth = Birth   # self.birth = 'Guangdong' 
. 6          Self. = Region Region   # self.region = 'Shenzhen' 
. 7  
. 8      DEF born (Self):
 . 9          Print (the self.name + ' born ' + self.birth)
 10  
. 11      DEF Live (Self):
 12 is          Print (the self.name + ' living in' + Self.region)    
 13  
14 the Person = Chinese ( ' Wu Feng ' , ' Guangdong ' , ' Shenzhen ' ) # incoming initialization method parameter 
15  person.born ()
 16 person.live ()

 

 

Guess you like

Origin www.cnblogs.com/k76x/p/11582598.html