Python Base Five, pythonbasefive
// 8 day)
38. In python, it is oop.
Class Baskball:
Def setName (self, name ):
Self. name = name
Def kick (self ):
Print ('My name is % s' % self. name)
Baskball = Baskball ()
Baskball. setName ('baskball ')
Baskball. kick ()
-> My name is baskball
Class Ball:
Def _ init _ (self, name ):
Self. name = name
Def kick (self ):
Print ('My name is % s' % self. name)
B = Ball ('Tom ')
B. kick ()
-> My name is tom
39. In python, how to define private variable,
Such:
Class Person:
Name = 'roy'
P = Person ()
Print (p. name)
-> Roy
If you use:
Class Person:
_ Name = 'roy'
P = Person ()
Print (p. _ name) | print (p. name)
-> Error
If you use _ before variable, you can access it direct.
Class Person:
_ Name = 'roy'
Def getName (self ):
Return self. _ name
P = Person ()
Print (p. getName ())
-> Roy
Class Person:
_ Name = 'roy'
P = Person ()
Print (p. _ Person _ name)
-> Roy
40. inheritance mechanic
Class SubClassName :( ParentClassName ):
......
Class Parent:
Def hello (self ):
Print ('write code change World ')
Class Child (Parent ):
Pass
P = Parent ()
P. hello ()
C = Child ()
C. hello ()
->
Write code change world
Write code change world
If subclass methon is same with parent, it will cover parent method, such:
Class Child (Parent ):
Def hello (self ):
Print ('believe youself ')
C = Child ()
C. hello ()
-> Believe youself
Now we will study a simple example:
Import random as r
Class Fish:
Def _ init _ (self ):
Self. x = r. randint (0, 10)
Self. y = r. randint (0, 10)
Def move (self ):
Self. x-= 1
Print ('my position is: ', self. x, self. y)
Class Shark (Fish ):
Def _ init _ (self ):
# Fish. _ init _ (self)
Super (). _ init __()
Self. hungry = True
Def eat (self ):
If self. hungry:
Print ('eat eat ')
Self. hungry = False
Else:
Print ('not hungry ')
1, Fish. _ init _ (self)
2, super (). _ init __()
1 and 2 is same, if you not add this, you invoke move in Shark, it will error, because ,__ init _ will cover parent method, you call move (), it will not found x and y. if you use 1 and 2, it will solve this question
Multiply parent class:
Class subClassName :( parent1ClassName, parent2ClassName ):
......
Class Base1:
Def fool1 (self ):
Print ('it is fool1 ')
Class Base2:
Def fool2 (self ):
Print ('it is fool2 ')
Class c (Base1, Base2 ):
Pass
C = c ()
C. fool1 ()
C. fool2 ()
-> It is fool1
-> It is fool2