Python18 object-oriented programming

Object-Oriented

  • Object-oriented programming: Object Oriented Programming
    • Acronym: OOP- the object as a basic unit procedure, an object contains function data and operational data.
    • Understand: object-oriented, is the relationship between class and instance, on the reality of human (including men, women) it is a class, a specific individual who is kind of a small army, called as an example
    • Baidu understand: https://baike.baidu.com/item/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/2262089?fr=aladdin
      - - - - - - - -
  • Classes and instances:
    • Class: it is abstracted templates, such as human
    • Definition method: class 类名(object):object is inherited classes, each object inherits by default
    • Code:
      # 创建类 class People(object): pass
    • Example: According to one class out of the concrete to create "objects", each object has a method of the same, but the respective data may be different.
    • Instructions:实例名 = 类()
    • Code:
      # 实例化类 man = People()
    • __init__: Initialize the class template, so that the value of the property can be obtained when the initialization
    • Code:
      class Student(object): def __init__(self,name,age): # self 这个值不用传 self.name = name # 属性 self.age = age bart = Student('小军','15') # 调用实例属性 print(bart.name,bart.age)
    • self: notice __init__ method of the first parameter is always self, represents create an instance of itself, therefore, within the __init__ method, you can put all kinds of property is bound to self, because it points to examples of self created itself.
    • Method: The class of functions, ordinary functions in a point that the first parameter is always self
    • Code:
      class Animal(object): # 属性(变量) name = 'xx' # 方法 def run(self): return self.name + '会跑' monkey = Animal() print(monkey.run())
      - - - - - - -
  • Data encapsulation: Class attribute defines a class method in the method, the internal properties are defined in the class, the data and logic is "encapsulated" up, it is easy to call, but do not know the details of the internal implementation.
    • Code:

      class School(object):
          def __init__(self,name,addr)
              self.name = name
              self.addr = addr
      
          # 定义一个方法 直接拿到属性
          def getProperty(self):
              return self.name,self.addr
      
          # 实例类
          school = School('mslg','America')
          sName,sAddr = school.getProperty()
          print(sName,sAddr)

  • Access restrictions: If you want the internal attributes are not externally accessible, you can put before the name of the property plus two underscores __, in Python, if the instance variable name starts with __, it becomes a private variable (private ), you can access only internal, not external access
    • Code:
      class Man(object): def __init__(self,name,age): self.__name = name self.__age = age def printNameAge(self): print(self.__name,self.__age) m = Man('a','12') print(m.__name) # 无法访问
    • Outside you can not access private variables: You can create a set method to set the value of a private variable, get method returns a value of private variables
    • Code:
      `` `
      class Student (Object):
      DEF the init (Self, name, Gender):
      the self.name name =
      Self .__ = Gender Gender # Private property
      def set_gender (self, gender): # Set value of private property, and parameter calibration
      IF Gender in [ 'MALE', 'FEMALE']:
      Self .__ = Gender Gender
      the else:
      the raise a ValueError ( 'Gender FEMALE or MALE iS')
      DEF get_gender (Self): # obtain private property value method
      return self .__ gender

      # Test:
      Bart = Student ( 'Bart', 'MALE')
      IF bart.get_gender () = 'MALE':!
      Print ( 'test failed!')
      The else:
      bart.set_gender ( 'FEMALE')
      IF bart.get_gender ( !) = 'FEMALE':
      Print ( '! test failed')
      the else:
      Print ( 'test successfully!')
      `
      - - - - - -
  • Inheritance and polymorphism: In OOP programming, if we define a class, they can inherit from an existing class, a new class is called a subclass (the Subclass), and inherited class called base class, parent class or super class (Base class, super class).
    • Code:
      # 定义一个Dog类继承Animal类 class Dog(Animal): pass # 继承之后就拥有了父类非私有方法和属性 d = Dog() print(d.run()) # 调用父类的run方法
    • For the Dog speaking, Animal is its parent class, for Animal speaking, it is a subclass of Dog
    • If the parent class and the class have the same method (the method name, the same number of parameters) method is invoked subclass
    • Code:
      # 定义一个Cat类继承Animal类 class Cat(Animal): name = 'dog' def run(self): return self.name + '会跑' c = Cat() c.run # 调用的是Cat的run方法 print(c.run())
    • The benefits of polymorphism is that when we need to pass Dog, Cat, Tortoise ......, we only need to receive Animal type on it, because Dog, Cat, Tortoise ...... all Animal type, and then follow the Animal type It can be. Since Animal types run () method, therefore, the incoming any type as long as the Animal class or subclass, will automatically call the actual type of run () method, which is polymorphic meaning:
    • Code:
      `` `
      # class is the data type
      the isinstance (C, Animal)
      the isinstance (C, Cat)
      Print (the isinstance (C, Animal), the isinstance (C, Cat)) # instance Cat is a Cat data type, but also Animal data type
      the isinstance (Monkey, Dog)
      Print (the isinstance (Monkey, Cat)) are not examples of Cat # Animal data type

      # Define a method of incoming Animal type
      DEF do_run (Animal):
      Print (Animal.run ())

      class Monkey(Animal):
      name = 'monkey'
      def run(self):
      return self.name + '会跑'
      # 调用
      do_run(Cat())
      do_run(Monkey())
      do_run(Dog())
      do_run(d)
      ```
      - - - -
  • Get Object Information:
    • types: determining whether an object is a function
    • Example:
      # types import types def fn(): pass type(fn) == types.FunctionType # 返回True
    • dir (): If all the attributes and methods of an object to be obtained, may be used dir () function, which returns a string containing the list, such as access to all properties and methods of an object str:
    • Code:
      `` `
      Print (the dir ( '123'))
      Print (the dir (Anmial ()))

      ```
    • getattr()、setattr()以及hasattr():
    • Code:
      `` `
      # getattr (), setattr () and hasattr (), we can directly manipulate the state of an object:

      class Demo(object):
      name = 'xxx123'
      age = 12
      def eat(self):
      print("eat!!!")
      demo = Demo()

      Are # hasattr (objects, properties) object has a property inspection, returns a Boolean value
      hasattr (demo, 'name') # have attributes name thing? True

      # Setattr (object attribute name, value) to set a property
      setattr (demo, 'addr', 'beijin')

      print (demo.addr) # get property

      # Getattr (object attribute) get property values
      getattr (demo, 'addr')

      print( hasattr(demo,'name') )
      print( getattr(demo,'addr') )
      ```
      - - - - - -
  • Examples of attributes and class attributes:
    • Examples of properties: Method a Python language is dynamic, an example of the class to create any binding property may be, for instance binding property is variable by way of example, or by the self variable:
    • Code:
      # 实例属性与类属性 class Test(object): name = 'Test.class' # 类属性,作用与类中,对象可以随意访问 def __init__(self,age): self.age = age # 实例属性 t = Test(12) t.addr = '123' # 实例属性 print(t.name) # 因为实例并没有name属性,所以会继续查找class的name属性 print(Test.name) t.name = '123.t' # 给t设置实例属性name print(t.name) # 123.t 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性 print(Test.name) # Test.class del t.name # 删除实例属性 print(t.name) # Test.class

Guess you like

Origin www.cnblogs.com/thloveyl/p/11440256.html
Recommended