Object-oriented design method , The two most important , One is code reuse , Encapsulate through inherited permission settings .
Python Class encapsulation and C++ The definition is similar , Just don't use keywords . But the definition of his type does not C++ Rich and strict .
CSDN This video is a very simple and clear expression of the design idea . however , The video is not easy to view , therefore , Here is a rewrite .
CSDN The definition given in the video of :
【xx】
【_xx】
【__xx】
class Apple():
def name(self,name):
self.__name = name
def getName(self):
return self.__name
A private attribute has been added here name, At the same time, an access function is set ,getName Go visit him .
class Apple():
def __setAge(self,age):
self.__age = age
def getName(self):
return self.__name
def info(self,age):
self.__setAge(age);
Just like private classes , Private methods can be defined . Private method calls , Within the definition of a class , Prefix is required 【self.】, The direct call will report an error
Corresponding to the situation that the skill tree is generally unable to run , I have compiled an example :
【 case , In this case , I wrote two private properties sex, and Married, A private function __SetPrivateMarriedx】
【 Call private properties directly , for example , Source code ,person.__sex = “ Man ”, It doesn't change the nature of gender , Still a woman , Until we call our preset interface access function SetSex, At the end of the article , We try to call private functions , The result is wrong , The data access permission is effectively protected .
person.__SetPrivateMarriedx(“Yes”)】
class People():
def __init__(self,name,work,sex,Married):
self.name = name
self.work = work
self.__sex = sex
self.__Married = Married
def Spyname(self,Spyname):
self.__name = Spyname
def getName(self):
return self.__name
def SetSex(self,Sex):
self.__sex = Sex
self.__SetPrivateMarriedx("Yes")
def __SetPrivateMarriedx(self,Married):
self.__Married = Married
def show(self):
print(" full name ",self.name)
print(" position ",self.work)
print(" Gender ",self.__sex)
print(" marriage ",self.__Married)
person=People(" Ordinary people ","good"," A woman ","no")
person.show()
person.name = " Mr Yu "
person.work = " New Oriental boss "
person.__sex = " Man "
person.show()
person.SetSex(" Man ")
person.show()
person.__SetPrivateMarriedx("Yes")
full name Ordinary people
position good
Gender A woman
marriage no
full name Mr Yu
position New Oriental boss
Gender A woman
marriage no
full name Mr Yu
position New Oriental boss
Gender Man
marriage Yes
AttributeError Traceback (most recent call last)
in
41 person.show()
42
—> 43 person.__SetPrivateMarriedx(“Yes”)
44
AttributeError: ‘People’ object has no attribute ‘__SetPrivateMarriedx’