The road of python self-study (5) JSON object-oriented

JSON

  • Serialized data cannot be used for data transfer in languages ​​==json== common to all languages ​​used

    import json

    dict1 = dict(name=’wang’,age=20)
    jsonO = json.dumps(dict1)
    jsonS = json.loads(jsonO)

    python standard library

    time os ...
    

    third party library

    import sys
    import time
    //Automatically find all storage directories for wooden blocks

custom library

引入自定义模块时不用加.py 
  1. Direct filename. The function is only referenced once,
    no matter how many times the import is used
  2. Don't want to be quoted adding restrictions

    if name == ' main ':
    function body

3. If imported as a custom module

__name__ = '模块的名字'
__all__ = ['demo','hello']:
    当使用了from use import *时候可以限制能够使用的函数只有demo和hello
__pycache__:
    当你第一次导入模块的时候会生成对应导入模块的文件

object oriented

object oriented

Format:

变量 = 类名()  【小括号不能省略】
class Person:
    def eat(self):
        print('eat')
    def sleep(self):
        print('sleep')

Object Orientation: Encapsulation, Inheritance, Polymorphism

  • When you see class Person(object): this naming is before 2.7 - object refers to the base class==
  • In 2.7* aftermarket class Person(object): called classic class
  • In 3.*, it is not necessary to write the classic class, which is removed and now has object by default

=='.' can be called member access symbol ==, member properties can be added dynamically

class Person:
    #成员属性
    name = ''
    #成员方法
    def eat(self):
        print('')

//成员属性存在就是读取值
koukou = Person()
print(koukou.name) //

Member properties and member methods

对象.属性名 #原来存在就是修改值 不存在就是添加值
对象.方法名() #调用成员方法

self:

每一个成员方法的形参开始第一个必须是self 并且不可以省略
对象.成员方法的时候不用传Self直接传后边方法就可以
**self:代表调用的当前对象**

self.name [Add or modify the member attribute value of the current object]

Construction method:

The method that is automatically triggered when an object is instantiated is called the object's constructor

def __init__(self[,args])
构造方法只有一个返回值None 构造方法不用手动调用
当你没有定义__init__的时候 默认系统会为你添加一个空的

Destructor

  1. In the program structure, it will be automatically called when the object is released
  2. Called automatically when an object is killed with del

    def del(self)

restriction of visit

私有方法和私有属性限制访问 即访问限制
"__"加到属性名前和方法名前 外部不能访问到
一般不在外部动态添加私有属性
在给私有属性设置值得时候可以通过这种方法过滤参数
    def setAge(self,age):
        if age<10:
            age = 25
        self.__age = age
  1. Try not to use super for multiple inheritance
  2. Inheriting parent-child property name conflict is best to use init initialization

inherit

继承具有传递性
单继承

class Fa:
    def run(self):
        print('11')

class Son(Fa):
    pass

nana = Son()
nana.run()

//当继承方法名发生冲突时要使用父级方法
super().方法名()

super().jiachan()

//Inherited modification (decorator)

@property

What is property?

==property is a special property that, when accessed, executes a piece of functionality (function) and returns a value ==

==The accessed property function cannot be assigned a value==

Why use property?

After defining a function of a class as a feature, when the object uses obj.name again, it is impossible to notice that its name is calculated by executing a function. The usage of this feature follows == unified access == the rules

ps:面向对象的封装有三种方式:
【public】
这种其实就是不封装,是对外公开的
【protected】
这种封装方式对外不公开,但对朋友(friend)或者子类(形象的说法是“儿子”,但我不知道为什么大家 不说“女儿”,就像“parent”本来是“父母”的意思,但中文都是叫“父类”)公开
【private】
这种封装对谁都不公开

Python does not syntactically build the three of them into its own class mechanism. In C++, all data is generally set as private, and then set and get methods (interfaces) are provided to set and obtain, This can be achieved by the property method in python

class Foo:
    def __init__(self,val):
        self.__NAME=val #将所有的数据属性都隐藏起来

    @property
    def name(self):
        return self.__NAME #obj.name访问的是self.__NAME(这也是真实值的存放位置)

    @name.setter
    def name(self,value):
        if not isinstance(value,str):  #在设定值之前进行类型检查
            raise TypeError('%s must be str' %value)
        self.__NAME=value #通过类型检查后,将值value存放到真实的位置self.__NAME

    @name.deleter
    def name(self):
        raise TypeError('Can not delete')

f=Foo('egon')
print(f.name)
# f.name=10 #抛出异常'TypeError: 10 must be str'
del f.name #抛出异常'TypeError: Can not delete'

multiple inheritance

Method execution order in multiple inheritance

==main --inheritance order --object==

overload

When inheriting, the conflict between the method name of the subclass and the method name of the parent class is called overloading. At this time, pay attention to use the parent class. Method name (self) to obtain

class attribute

  • Class property does not belong to an object
  • It belongs to the class name and attribute name of the entire class calling method
  • In general, it is required not to define class attributes in the class or not to use the same attribute name

    class Person:
    name = ‘ww’
    ren = Person()
    ren.name = ‘dede’
    print(ren.name) //dede
    del ren.name
    print(ren.name) //ww

Class methods and static methods

====Pay attention to note====: Although static methods and class methods are prepared for classes, they can also be used if they are used by instances, but it is easy to confuse people when they are called by instances. I don't know you. what to do

class method

The class method is for the class. When the class is used, it will pass the class itself as the parameter to the first parameter of the class method. Python has built-in function classmethod for us to define the function in the class as a class method.

==@classmethod==

class Person:
    def demo(self):
        print('demo')
    @classmethod
    def test(cls):   //cls指的就是Person类
        obj = cls()
        obj.demo()
        print('hh')

static method

==@staticmethod==

class Person:
    def demo(self):
        print('demo')
    @staticmethod
    def heng(self):
        self.demo()
        print('sss')

#在实例化使用时 self也要传递
d = Person()
d.heng(d)

#直接调用  不实例类
d = Person()
d.heng()
class Foo:
    @staticmethod #装饰器
    def spam(x,y,z):
        print(x,y,z)
Foo.spam(1,2,3)

Advantages of static member methods: No need to instantiate, no need for new, can be called directly

Application scenario: There are many different ways to create instances when writing a class, and we only have one init function, at which point static methods come in handy

class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    @staticmethod
    def now(): #用Date.now()的形式去产生实例,该实例用的是当前时间
        t=time.localtime() #获取结构化的时间格式
        return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回
    @staticmethod
    def tomorrow():#用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间
        t=time.localtime(time.time()+86400)
        return Date(t.tm_year,t.tm_mon,t.tm_mday)

a=Date('1987',11,27) #自己定义时间
b=Date.now() #采用当前时间
c=Date.tomorrow() #采用明天的时间

print(a.year,a.month,a.day)
print(b.year,b.month,b.day)
print(c.year,c.month,c.day)

str usage

#__str__定义在类内部,必须返回一个字符串类型,
#什么时候会出发它的执行呢?打印由这个类产生的对象时,会触发执行

class People:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        return '<name:%s,age:%s>' %(self.name,self.age)

p1=People('egon',18)
print(p1)
str(p1) #----->p1.__str__()

Dynamically add properties and methods

Dynamically add classes

Parameters: type (class name, object[,...], dict (attribute key-value pair, method key-value pair))

p = type('Person',(object,),dict(name = 'www',demo = hello))

Dynamically add properties

class Person:
aa = Person()
aa.stu = 'dada'  //动态的添加属性

add method dynamically

  1. Dynamically add member methods

    class Person:
    pass
    def demo (self):
    print ('dongtai')
    aa = Person ()
    aa.test = demo
    aa.test (aa)

  2. Reference module dynamic binding method

    from types import MethodType

    class Person:
    pass

    def demo (self):
    print ('dongtai')
    aa = Person ()
    aa.test = MethodType (demo, aa)
    aa.test ()

You can also use special properties to limit dynamically added properties

__slots = (‘name’,’age’,’height’)

That is, except for name, age, height, other attributes cannot be dynamically added

Commonly used properties

Person.__name__ //返回的是类名      
Son.__bases__   //获取当前类的父类      
Son.__base__    //获取当前类的父类      
Son.__dict__    //把成员方法序列返回

polymorphism

The same method has many different functions in different environments

Code modifications are closed extensions are open

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324724727&siteId=291194637