python base (12): object-oriented programming

First, object-oriented

Programmatically

  • Process for: the business logic code from top to bottom barrier.
  • Functional: The function of a package to function, you need not be repeated in the future to write, you can call the function only.
  • Object-oriented: the classification and packaging of the function, allowing developers to "faster and better and stronger ......"

What is object-oriented:

        Object-oriented process is not divided by function-oriented as a module, it is concerned that there is a software system which participants, the participants called objects, to identify these software systems participants it is behind the object, analysis of these objects What are the characteristics, behavior and relationships between objects which, so that object-oriented development core is subject .

What are the categories:

        Object-oriented programming two very important concepts: Classes and Objects

        Class is a type of object that has the same properties and behavior collectively things. Class is the abstract of the (non-existent), when in use will usually find a specific class of existence .

What is the object:

        Everything object, the object has its own characteristics and behaviors.

The relationship between classes and objects:

        Class is a type of object, the object is an instance of a class. Class is an abstract concept, and the object is a tangible but you can get entity. Two complement each other, who can do without.

Class consists of three parts:

  • Name of the class: type
  • Properties: properties of the object
  • Methods: The object

Second, the creation and use:

Class definition:

class 类名:
    属性列表
    方法列表

Example:

'''
类定义
class 类名():
    # 类文档说明
    属性
    方法
'''

class person():
    '''
    这是一个人类
    '''
    country = '中国'   # 声明类属性并赋值
    
    # 实例属性通过构造方法来声明
    # self不是关键字,代表的是当前对象
    def __init__(self, name, age, sex):     # 构造方法
        # 构造方法不需要调用,在实例化的时候自动调用
        print('我是构造方法,在实例化的时候调用')
        self.name = name            # 通过self创建实例属性,并且赋值
        self.age = age
        self.sex = sex
        
    # 创建普通方法
    def getName(self):
        print('我的名字叫:%s,我来自%s'%(self.name, person.country)) # 在方法里面使用实例属性
        
# 实例化对象
people1 = person('joe', 1, '男')  # 在实例化的时候传进参数
# 这个people1就要具有三个属性,并且可以使用getName方法

# 访问属性
print(people1.name)  # 通过对象名.属性名 访问实例属性(对象属性)

# 通过对象调用实例方法
people1.getName()
# output:我的名字叫:joe,我来自中国

__init __ () constructor and self:

  • __init __ () is a special method, proprietary methods belong to the class, called a constructor class or initialization method, a method of front and rear two underscores.
  • This is to avoid default Python method and common method name conflict occurs. Whenever create an instance of the object class of, __ init __ () method will be run by default. The role of the object is instantiated after initialization.
  • In the process definition, the first parameter is essential self. Difference method of the class and normal function is self, self is not a Python keyword, you can use other words to replace, but in accordance with the practices and standards, it is recommended to use self.

Property classification class (people create a class):

  • Class Properties
  • Instance Properties
  • Class variables: Class variables are common throughout the instantiated object. And class variables defined outside the body of the function in the class. Class variables are typically not used as instance variables. If needed, the function using the class name. Class attribute .
  • Examples of variables: variables defined in the process, only the role of the current instance of the class.

Some methods for the properties of the class:

  • It can be used to instantiate an object name + to access the object's properties
  • You can also use what function the way to access the property
'''
getattr(obj, name[, default]): 访问对象的属性
hasattr(obj, name): 检查是否存在一个属性
hasattr(obj, name, value): 设置一个属性。如果属性不存在,会创建一个新属性
delattr(obj, name): 删除属性
'''
print(getattr(people1, 'name'))  # output:joe
print(hasattr(people1, 'name'))  # output:True

setattr(people1, 'name', 'susan')
print(people1.name)     # output:susan

delattr(people1, 'name')
print(people1.name)         
# output:AttributeError: 'person' object has no attribute 'name'

Built-in class attribute:

Python built-in class attribute:

  • the __dict__: class attributes (including a dictionary, the name of the class attribute: value of) instances of the class name .__ dict__
  • __doc__: Class documentation strings (Class name) to instantiate the class name .__ doc__
  • __name__: class name, implementation class name .__ name__
  • __bases__: All the elements constituting the parent class (containing neuron progenitor of all of the parent classes)
'''
内置类属性
'''
print(people1.__dict__)
# output:{'age': 1, 'sex': '男', 'name': 'susan'}
# 会将实例对象的属性和值通过字典返回

print(people1.__doc__)
# output:这是一个人类

print(person.__name__)  # 返回类名
# output:person

print(person.__bases__)
# output:(<class 'object'>,)

 __name__

  • __name__: If the module is placed Modules, it means that the module name; if it is placed in class Class, it means the name of the class;
  • __main__: module, xxx.py file itself, when it is executed directly, the corresponding module name is a __main__. Can "__main__" in if __name__ ==: you want to add, for the test module, the module demonstrates the use of the code and so on.
  • When a module is introduced into other Python programs (import), the module name itself is the file name XXX.

 Example:

Suppose there are two files, one is name1.py:

def a():
    print('我是a方法')

print(__name__)
# output:__main__

Output:

Another file is name2.ph:

import name1

 Output:

When tested, the name1.py can be written as:

def a():
    print('我是a方法')
if __name__ == '__main__':
    a()

That is, only the current script is running, run a (), when introduced into other scripts, do not run a ().

 

Third, inheritance, and polymorphism

inherit:

        Program, describes the inheritance belongs relationship between things, such as cats and dogs are all animals, the program can be described as cats and dogs are inherited from animals. Similarly, domestic cats and Persian cats are inherited from. The program, when we define a class, they can inherit from an existing class, a new class is called a subclass (subclass), is called a base class inherit the class parent class or superclass. Subclass inherits all the attributes and methods of its parent class, but you can also customize your own properties and methods.

        Python when multiple inheritance, i.e., a plurality of subclasses inherit the parent class.

class Animal():
    def __init__(self, name, food):
        self.name = name
        self.food = food
        
    def eat(self):
        print('%s爱吃%s'%(self.name, self.food))
        
# Dog类继承Animal
class Dog(Animal):          # python中的继承,只要把父类名写在括号里就行
    def __init__(self, name, food, drink):
        super().__init__(name, food)      # 加载父类中的初始化方法
        self.drink = drink
    def drinks(self):
        print('%s爱喝%s'%(self.name, self.drink))
        
# Cat类继承Animal
class Cat(Animal):
    def __init__(self, name, food, drink):
        super().__init__(name, food)
        self.drink = drink
    def drinks(self):
        print('%s爱喝%s'%(self.name, self.drink))
        
# 子类(Dog和Cat)继承了父类(Animal)的全部功能,自动拥有了父类的eat()方法
dog1 = Dog('小狗','骨头','肉汤')
dog1.eat()
dog1.drinks()

cat1 = Cat('小猫','鱼','牛奶')
cat1.eat()
cat1.drinks()

Output:

Multiple inheritance:

python in multiple inheritance syntax is as follows:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    ...
    ...
    <statement-1>

        Note that the order in parentheses parent, if the parent class have inherited the same method name, but did not specify when used in a subclass, python from left to right to find the parent class contains methods ah. 

class A():
    def a(self):
        print('我是A里的a方法')
        
class B():
    def b(self):
        print('我是B里的b方法')
        
class C():
    def c(self):
        print('我是C里的c方法')
        
class D(A, B, C):
    def d(self):
        print('我是D里的d方法')
        
dd = D()
dd.a()
dd.b()
dd.c()
dd.d()

 Output:

Fourth, the class and instance properties

Attributes:

        Try to require users to pass the attributes property as an example, but the same kind of properties as a class property. In every instance property and create a class will be initialized again, examples of the properties of different instances may not be the same, different instances of the class attributes are tantamount.

Example 1. Properties:

        In the __init __ (self, ...) is initialized

        You need to add self internal call.

        With "object name attribute name" external call to call

2. class properties:

        Initialization __init __ () in

        In internal use classname. Class attribute name calling

        External either be called with classname. Class attribute name, they can use instancename. Class attribute name

3. Private Properties:

        The beginning (1) double underlined __: external access or not to change the "object name attribute name." Actually converted to "_ __ class name attribute name"

class person():
    '''
    这是一个人类
    '''
    country = '中国'   # 声明类属性并赋值
    
    # 实例属性通过构造方法来声明
    # self不是关键字,代表的是当前对象
    def __init__(self, name, age, sex, address):     # 构造方法
        # 构造方法不需要调用,在实例化的时候自动调用
        print('我是构造方法,在实例化的时候调用')
        self.name = name            # 通过self创建实例属性,并且赋值
        self.age = age
        self.sex = sex
        self.__address = address # 双下划线开头的属性是私有属性
        
    # 创建普通方法
    def getName(self):
        print('我的名字叫:%s,我来自%s'%(self.name, person.country)) # 在方法里面使用实例属性
        
# 实例化对象
people1 = person('joe', 1, '男')  # 在实例化的时候传进参数

# 通过对象名.属性名访问私有属性
print(people1.__address)

 输出:AttributeError: 'person' object has no attribute '__address'

        Private property can only be used in the class!

Or Mandatory Access:

print(people1._person__address)

Output: 

Or: External To modify private property, set aside or modify an excuse to visit a private property. For example, the following method may be applied within the class.

def getAddre(self):
    return self.__address

 Single underline, double underline, double underline head and tail description:

  • __foo__: definition is a special method, similar __init __ () or the like.
  • _foo: starting with single underlined is protected types of variables, namely the protection type can only allow it to itself and the subclass access (instances created can be accessed), can not be used from module inport *
  • __foo: double underline indicates the type of private (private) variables can only be allowed to access the class itself.

Fifth, access restrictions

  • Set to private property can not be accessed directly through the property of the object, but can be accessed directly through the "instantiating an object class name __ ._ property name." But doing so is not recommended. Different versions of the Python interpreter might suggest '__ attribute name "into a different variable names. Overall, python does not have any mechanism to stop you from doing bad things, all thanks to the conscious.
  • By "object name .__ attribute name" to directly modify private property. On the surface it seems changed, in fact, did not. Because the interior of the python interpreter object has attribute name interpreted to mean "__ _ class name attribute name." If you modify a statement outside the equivalent of another property.
people1.__address = '上海'
# 看上去改了,其实没有。你给当前对象声明了一个新属性

print(people1.__address)
print(people1.getAddre())

Output:

Sixth, class methods, and static methods 

1. The common method:

def fun_name(self, ...):
    pass
外部用实例调用

2. static methods: by decorator @staticmethod decoration

  • You can not access the instance properties
  • Parameters can not pass self
  • But unrelated to the class instance does not depend on the method of
    # 创建一个静态方法
    @staticmethod
    def aa():           # 不需要传递实例
        print('我的名字叫:%s'%self.name)

people1 = person('joe', 1, '男')
people1.aa()

We will complain: name 'self' is not defined

So you can only access the class properties :

    # 创建普通方法
    def getName(self):
        print('我的名字叫:%s,我来自%s'%(self.name, person.country)) # 在方法里面使用实例属性
        
    # 创建一个静态方法
    @staticmethod
    def aa():           # 不需要传递实例
        print('我来自:%s'%person.country)

people1 = person('joe', 1, '男')
people1.aa()

Output:

3. Method categories: @classmethod

  • You can not access the instance properties
  • Parameters must be passed cls (which represents the object of such distinction, self representatives instance object), and use this to call mine property:. Cls class attribute name
    # 类方法
    @classmethod
    def bb(cls):        # class   也不是关键字
        # 类方法不能访问实例属性
        print('我的名字叫:%s'%cls.country)  # 就用cls访问类属性
        
people1 = person('joe', 1, '男')
people1.bb()

Output:

        Static methods and class methods can be invoked through the class or instance. Features are not calling instance properties. Static method does not accept arguments, using the class name. Class Properties

Guess you like

Origin blog.csdn.net/qq_26271435/article/details/89812826