#### python's object-oriented ###

Object-oriented and process-oriented ## ##

Is a process-centric programming ideas: process (Procedure Oriented) face. With the main objective of the program is taking place, it is to analyze the steps needed to solve the problem and then use the function to implement these steps, step by step, one by one when using a single call.
1. All steps are completed from start to finish a certain demand gradually
according development requirements, certain functions into a separate code and a function package
3. Finally finished code is to call a function in a different order
features:
1. focus on the steps and processes, does not focus on the division of responsibilities
2. If the demand for complex code becomes very complicated
3. develop complex project, there is no fixed routine, it is very difficult to develop
object-oriented (Object oriented Programming): short oop , a design program, the program as a basic unit of an object, an object contains function data and operational data;

Comparison function, object-oriented is larger packages, packaged in a plurality of method functions according to the object
1 before the completion of a demand for a first determined duty - to do (method)
2. Determine the different objects under the responsibility in the interior of the object different encapsulation method (multiple)
3. finalization of the code, so that is the order of the different objects in different ways call
features:
1. focus on objects and responsibilities, different objects assume different responsibilities
2. more suitable for complex changes in demand, specially developed to deal with complex projects, providing fixed routine
3. need in process-oriented basis, and then learn some object-oriented syntax

Object-oriented concept has two core
classes: is a general term for a class of things having the same characteristics or behavior of
an object: a concrete existence created out of the class
relations and class objects: first class and then have the object
class is a template object this is based on a template created out of
class just to have an object can have multiple

Class: attribute (common information such matters) and method (you can complete the action)
1. class name: The name of these things (big hump nomenclature)
: a large hump nomenclature
first letter of each word 1 capital
is not between the word and the word is underlined 2.
2. attribute: this class creates objects out what characteristics
3. methods: this class creates objects out what behavior
### for the definition of an object ###
to create a fruit
properties: name
method: color, flavor

class frutes():
    def sweet(self):  ##一个
        print('%s味道很甜')
    def colour(self):
        print('颜色是红色')
print(frutes())  #调用函数,显示内存地址
#创建一个对象
apple = frutes()
print(apple) #调用函数,显示内存地址
frutes.name = 'Apple'
print(frutes.name)
apple.colour()
apple.sweet()

banana = frutes()
print(banana)
banana.sweet()
banana.colour()

Create a method in the class definition when the self argument

A method which is called an object, which is the self reference to a function object; process inside the package, it means that the current self calling method when the object itself, it is not necessary at the time of call parameters passed self (defined by the first parameter must be self)

class Cat:
    def __init__(self,name,color):
        self.name = name
        self.color = color
    def get_name(self):
        print('name is %s' %self.name)
    def get_color(self):
        print('color is %s' %self.color)

tom = Cat('Tom','blue')
erpang = Cat('pang','yellow')   # 实例化两个对象
#两个对象是使用同一个类创建出来的,但是其数据不一致,相互之间没有关系

tom.get_color()  # 当对象调用方法的时候,其中self参数就是调用方法的对象本身
tom.get_name()

erpang.get_color()# 当对象调用方法的时候,其中self参数就是调用方法的对象本身
erpang.get_name()

输出结果:
color is blue
name is Tom  
 #当调用方法的对象是tom的时候,self参数就是引用的该对象,输出都是实例化该对象的时候,设置的属性

color is yellow
name is pang
 #当调用方法的对象是erpang的时候,self参数就是引用的该对象,输出都是实例化该对象的时候,设置的属性

### initialization method __init __ ###
this initialization method is built-in method, is designed to define a class, according to what properties and methods
because the class can act as a template, so you can create an instance of the time, the Some believe we must bind attribute mandatory to fill in. By defining a special __init__ method, when creating the instance, put name, score and other properties tied to
notice __init__ method of the first parameter is always self, it represents create an instance of itself, therefore, in _ internal _init__ method, you can put all kinds of property is bound to self, because the self is created to point to an instance of itself.
With __init__ method when creating instances, empty parameter can not pass, and pass parameters must match the __init__ method, but do not need to pass self, Python interpreter himself will pass in an instance variable .

Use: the class name () can create an object, when creating an object, Python interpreter automatically performs the following operations: 1 allocate space for the object in memory - create objects; 2 calls the initialization method attribute is set to the object. the initial value.

When you create an object of setting properties of the object. Using default initialization method attribute set.

1.把希望设置的属性值,定义成__init__方法的参数
2.在方法内部使用self.属性名 = 形参 接收外部传递的参数
3.在创建对象的时候,使用类名(属性)调用
class frutes():
    def __init__(self, new_name):   ##初始化方法
       self.name = new_name
    def sweet(self):
        print('%s味道很甜' %(self.name))
    def colour(self):
        print('%s颜色是红色' %(self.name))
       #print(frutes())  #调用函数,显示内存地址
#创建一个对象
apple = frutes('Apple')
print(apple) #调用函数,显示内存地址
apple.colour()
apple.sweet()

banana = frutes('Banana')
print(banana)
banana.sweet()
banana.colour()

#### str method ###
want to use the print output target variable, the ability to print customized content can take advantage of the built-in method of __str__. But the contents of the output can only be string type.

Use print output when the object variable, the variable output by default will be referenced object is an object created by a class and which address in memory

The default output:

class frutes():
    def __init__(self, new_name):
       self.name = new_name
    def __str__(self): #返回的必须是一个字符串
        return '我是%s' %(self.name)
    def sweet(self):
        print('%s味道很甜' %(self.name))
    def colour(self):
        print('%s颜色是红色' %(self.name))
       #print(frutes())  #调用函数,显示内存地址
#创建一个对象
apple = frutes('Apple')
print(apple) #调用函数,显示内存地址
apple.colour()
apple.sweet()

banana = frutes('Banana')
print(banana)
banana.sweet()
banana.colour()


## hex change

class frutes():
    def __init__(self, new_name):
       self.name = new_name
    #def __str__(self): #返回的必须是一个字符串
    #    return '我是%s' %(self.name)
    def sweet(self):
        print('%s味道很甜' %(self.name))
    def colour(self):
        print('%s颜色是红色' %(self.name))
       #print(frutes())  #调用函数,显示内存地址
#创建一个对象
apple = frutes('Apple')
print(apple) #调用函数,显示内存地址
apple.colour()
apple.sweet()
addr = id(apple)

banana = frutes('Banana')
print(banana)
banana.sweet()
banana.colour()
addr = id(banana)  #输出内存地址
print('%x' %(addr))  #转化成十六进制
print('%d' %(addr))  #转换成10进制的方法

## del ###
if the class is defined __del__ methods, when you use this class to instantiate an object when it is deleted (this object is removed from memory out), it will automatically call the method.

class frutes():
    def __init__(self, new_name):
       self.name = new_name
    def __del__(self): #返回的必须是一个字符串
        return '我是%s' %(self.name)
    def sweet(self):
        print('%s味道很甜' %(self.name))
    def colour(self):
        print('%s颜色是红色' %(self.name))
       #print(frutes())  #调用函数,显示内存地址
#创建一个对象
apple = frutes('Apple')
print(apple.name) #调用函数,显示内存地
del apple  ##删除

print("*" * 50)
print(apple.name)

Exercise:
a first extraction number stack, the stack (last-out) into a first final value, there

class Stack:   #创建一个类
    def __init__(self):  #初始化一个列表
        self.stack = []
    def push(self,value):  #往栈里输入值
        self.stack.append(value)
        return True
    def pop(self):   ##判断栈里是否存在值 
        if self.stack:
            item = self.stack.pop()  #定义一个变量接受pop弹出的值
            return item
        else:
            return False 
    def top(self):
        if self.stack:
            return self.stack[-1]  #取出栈里的第一个值
        else:
            return False
    def length(self):   #栈的长度
        return len(self.stack)
    def view(self):   
        return ','.join(self.stack)  #用,连接栈内的值
s= Stack() 调用函数
s.push('1')
s.push('2')
s.push('3')
item = s.pop()  #弹出值
print(s.view())

取出队列的第一个数
class Stack:
    def __init__(self):
        self.stack = []
    def push(self,value):
        self.stack.append(value)
        return True
    def pop(self):
        if self.stack:
            item = self.stack.pop(0)
            return item
        else:
            return False
    def top(self):
        if self.stack:
            return self.stack[0]
        else:
            return False
    def length(self):
        return len(self.stack)
    def view(self):
        return ','.join(self.stack)
s= Stack()
s.push('1')
s.push('2')
s.push('3')
item = s.pop()
print(s.view())

Exercise

class Person:
    def __init__(self,name,weight):
         self.name = name
         self.weight = weight
    def __str__(self):
        return '%s的体重是%.2f' %(self.name,self.weight)
    #在对象的方法内部,可以直接访问对象的属性
    def run(self):
        print('%s跑步' %(self.name))
        self.weight -= 0.5
    def eat(self):
        print('%s吃饭' %(self.name))
        self.weight += 1
xiaoming = Person('小明',75)
xiaoming.run()
xiaoming.eat()
print(xiaoming)
xiaomei = Person('小美',45)
xiaomei.eat()
xiaomei.run()
print(xiaomei)

1, the new class and legacy (classic) class
new categories: base object class class
Classic: a class object is not in the base class

When python3.X defined in the class, if the parent class is not specified, the default will be used as a base class object -python3.x new class are defined

When python2.x defining classes, if no parent class is not a base class object to

To ensure that the code can be written simultaneously in python2.x and python3.x run, in the future when defining the class, if no parent, the proposed unified inherit from object
2, class attributes and class methods

Class properties: the properties defined for the class itself, the use of an assignment statement can define attributes in the class keyword class, classify all such property itself. Use the class name. Property called class attributes

When we define a class attribute, although classified all, but all instances of the class have access to, and when there is no instance of this property, it will continue to look for this class of property

3, private property and private methods

Private property: the front with two variables underlined privatization, the privatization of property after property belonging to the interior of the class can be accessed internally, not just can not be accessed or modified.

Private methods: Method name in front with two underlined the privatization method, can be called internally, you can not use an instance to call the method of privatization on the outside.

The method is defined
in the definition of a property or method, add two underscore, is the definition of private property or method before property name or method name
4, static methods

If you need to define a method in the class, this method does not require instance properties do not need to call instance method; neither the property does not need to call the access class class method, this time this method can be packaged as a static method. Use the keyword set @staticmethod

5, the design pattern - singleton
design pattern:

Design pattern is a summary of previous work and refining, generally, people are widespread design patterns are proven solutions for a particular problem, the use of design patterns to reusable code, make the code easier to understand others, to ensure that reliability codes
singleton design pattern:

Objective: To let the class to create objects, there is only one instance of each execution object returned by the class name () in the system memory address is the same

Use __new __ (cls) implemented method of singleton design pattern:

We create an object with the class name. The way time, python interpreter will help us to do two things,
1. The space allocated for the object

__new__是一个由object基类提供的内置的静态方法,主要有两个作用: 在内存中为对象分配空间 返回对象的引用
new:负责给对象分配空间,并返回对象的引用给初始化方法

2. Object Initialization

__init__(初始化方法)负责给对象初始化.
解释器获得对象的引用后,将引用作为第一个参数,传递给__init__方法

Guess you like

Origin blog.csdn.net/weixin_44821839/article/details/91874379