08.07 Object-Oriented

Access Visibility

  • Private variable, the variable name preceded by "__"
  • Private can not be inherited, can not call outside, but you can call internally.
  • If you have to use private variables, you can use dir (class ()) to view its real name.
  • Private variables / functions within the class can be called directly.
  • If you want to reflect a variable / function is particularly important that you can use the "_"
#私有
class
A(object): def __init__(self): self.__a=1000 self.__b=100 def __B(self): print(self.__a) self.c() def __c(self): print(self.__a) A_=A() print(A_._A__a)

@property decorator and @ .setter decorator

Decorator when the need to pay attention to:

  1. Decorator names, function names needs to be consistent.
  2. property need to declare, write setter, the order can not be reversed
  3.  If you want just a little variable is accessed can not be modified, you can use accessor @property
  4. If you want to modify the accessor variables can build a modifier, or remove access control.
#装饰器的使用
class
Name(object): def __init__(self,a,b): self.__a=a self.__b=b @property def A (self): print(self.__a) name=Name(00,200) name.A

 

#修改器的使用
class Name(object):
    def __init__(self,a,b):
        self.__a=a
        self._b=b
    @property
    def A(self):
        print(self.__a)
    @A.setter
   def A(self,a1):
    self.__A=a1
   def play(self):
    print(self.__a)
    print(self.__b)
name=Name(100,200)
name.A=1000
name.play()
  • Examples: Input three numbers (private), and find three numbers, which try to change the two numbers
class A(object):
    def __init__(self,a,b,c):
        self.__a=a
        self.__b=b
        self.__c=c
    @property
    def B(self):
        print(self.__a)
    @B.setter
    def B(self,num):
        self.__a=num
    def sum(self):
        print(self.__a+self.__b+self.__c)
a=A(12,1,4)
a.B=99
a.sum() 

In python class is dynamic.

class Num(object):
    def __init__(self):
        self.a = 1000
    
    def A(self):
        print(self.b)


num = Num()
num.b =1000000
# print(num.a)
print(num.b)
num.A()

_ _ Slots _ _ Magic

       We are talking about this, I do not know whether you have realized, Python is a dynamic language . Typically, dynamic languages allow new property or method we bind to the object in the running, of course, can unbind the properties and methods have been bound. But if we need to define custom type of object can only bind certain attributes can be defined by class _ _ slots _ _ variable to be defined. Note that _ _ slots _ _ limited only to the current class of objects into effect, sub-class does not play any role.

class Person (Object):
     # define Person object can only bind _name, _age properties and --gender 
    __slots__ is = ( ' the _name ' , ' _age ' , ' 's _gender') 
    DEF  the __init__ (Self, name, Age): 
        Self. __name__ = name 
        Self. __age = Age

 

Guess you like

Origin www.cnblogs.com/lxq0727/p/11315756.html