Python study notes --Day04

Python study notes --Day04

The fourth day, continue to fuel, object-oriented start

class

Using the class keyword to define classes and methods defined by a function previously learned in class, and then create an object, so that you can go through some of the data objects stored or call the appropriate behavior. First look at a sample code

class Person(object):

    def __init__(self, name, age, father):
        self.name = name
        self.age = age
        self.__father = father

    def __speak_father(self):
        print("my father is", self.__father)

    def speak(self):
        print("I'm a person, and my name is %s, and I'm %d years old" % (self.name, self.age))


def main():
    person1 = Person("zhangsan", 12, "zhanger")
    person2 = Person("lisi", 13, "lisan")
    person1.speak()
    person2.speak()
    # person2.__speak_father()
    # 访问私有方法
    person2._Person__speak_father()


if __name__ == "__main__":
    main()

In this code, __ init__ method is equivalent to the constructor in Java, the initialization operation is carried out when you create an object, __ speak_father this method is a private method, the provision is not that we want to call this method through an object directly, but in fact we have to call the main method by the way, but that would break the rules, do not recommend such operations, beginning with an underscore _ method is a protected method, only an object of this class or sub-class object to call, speak the method is a common method, as long as the Person object can go call this method.

Object-oriented basis

Object (Object Oriented, OO) is a software-oriented development methodology, refers to the use of object-oriented programming in the package, inheritance, polymorphism and other design methods, object-oriented development of these three is the most important of the three characteristics, we look one by one What is the package, the hidden object's properties and implementation details, just outside the provision of public access, so when we use these objects, our relations are only open interface, do not need to know the implementation details, and the code encapsulated, the coupling can be reduced to some extent, improve the reusability of code. Inheritance is the relationship between class and class, the class definition that already exists as a basis to define a new class based on this new class can extend a new property or method, you can use the parent class defined Features. Polymorphic boils down to is the parent class references to subclass objects, this sentence is Java often said, what does that mean, that is a reference to an object instance variable in the end what kind of point, the reference variable method call is issued which class methods implemented must be decided before the program is running. About object-oriented, I will not describe in detail, the specific can go and see "Thinking in java" inside the introduction, the amount, because when I learned Java to see this part impressed, it is recommended that you also take a look, reading this book impressed me most is the phrase, "everything is an Object", as well as philosophical point of meaning in it, specifically what it means to explore it on their own.

@property decorator

The above example shows the Person of the property, two public and one private, there are two ways that we do not recommend, after all, the object's properties directly exposed to the outside world is a problem, so we these attributes are set to protected, has been mentioned above, it is to add an underscore _.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:@property包装器包装getter和setter方法


class Person(object):

    def __init__(self, name, age):
        self._name = name
        self._age = age

    @property
    def name(self):
        return self._name

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, age):
        self._age = age

    @name.setter
    def name(self, name):
        self._name = name

    def speak(self):
        print("I'm a person, and my name is %s, and I'm %d years old" % (self._name, self._age))


def main():
    person = Person('zhangsan', 12)
    person.speak()
    person.age = 11
    person.name = 'lisi'
    person.speak()
    print(person.age)


if __name__ == "__main__":
    main()

This subparagraph title is what this means, it is an access device to provide a getter method, the code @name.setterused to provide setter methods, because we still need to modify the corresponding attribute value, so these two accessors to do modification and access. Directly through the 对象名.属性名way we can do it.

__slots__ use

Not just introduced to, python is a dynamic language, is the new property or method we can bind to the target in the program is running, you can also unbundling of the properties and methods had been bound. And __slots__is capable of binding properties of the object to be limiting, the object class can be bound to limit the tuple attributes.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:slots的使用


class Person(object):

    __slots__ = ('_name', '_age', '_gender')

    def __init__(self, name, age):
        self._name = name
        self._age = age

    @property
    def name(self):
        return self._name

    @property
    def age(self):
        return self._age

    @name.setter
    def name(self, name):
        self._name = name

    @age.setter
    def age(self, age):
        self._age = age

    def speak(self):
        print("I'm a person, and my name is %s, and I'm %d years old" % (self.name, self.age))


def main():
    person = Person('zhangsan', 12)
    person._gender = '男'
    print(person.name)
    print(person._gender)
    person._nana = "nana"
    print(person._nana)


if __name__ == "__main__":
    main()

This code you can run it, and then look at the console information fell into place.

Static methods and class methods

Static method is that you can directly through the class name to call a method, similar to the class methods and static methods, the first parameter convention called cls, it represents the current class of objects relevant information, we can get through this parameter and the associated class information and can create objects out of class.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:静态方法和类方法


class AddUtil(object):

    @staticmethod
    def add(*num):
        total = 0
        for item in num:
            total += item
        print(total)

    @classmethod
    def add_num(cls):
        return cls.add(1, 1, 1)


def main():
    AddUtil.add(1, 1, 1, 1, 1, 1)
    AddUtil.add_num()


if __name__ == "__main__":
    main()

Rewrite method

Subclass inherits the parent class may have to rewrite the existing parent class, by rewriting, we can make different subclasses call the same interface to exhibit different behavior is polymorphic mentioned above.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:方法的重写
from abc import abstractmethod, ABCMeta


class Person(object, metaclass=ABCMeta):
    """人类"""

    @abstractmethod
    def speak(self, name):
        pass


class Student(Person):
    """学生类"""
    def speak(self, name):
        print("%s是本学生的名字" % name)


class Worker(Person):
    """工人类"""
    def speak(self, name):
        print("%s是本工人的名字" % name)


def main():
    student = Student()
    student.speak("zhangsan")
    worker = Worker()
    worker.speak("lisi")


if __name__ == "__main__":
    main()

There is the Person class defines an abstract method, thus Person class is an abstract class, abstract class is not to create objects of the class is to allow other classes to inherit this class and then implement the appropriate function, you can abcblock ABCMetametaclass and the abstractmethodwrapper to achieve an abstract class, the above method Speak code Person class is an abstract method, thereby can not create the Person class objects.

file

Data persistence operations actual development, the most direct way is saved to a file. Only write python files is very simple, built-in open function, you can specify a file name, mode of operation, such as access to files encoded information object can manipulate files, then you can only write to the file. Operating mode table below (Table python tutorial files and Luo Hao exception of 100 days).

Mode of operation Specific meaning
'r' Read (default)
'w' Write (previous content will first cut-off)
'x' Write, if the file already exists generates an exception
'a' Append, write the contents to the end of an existing file
'b' Binary mode
't' Text mode (default)
'+' Update (both read and can write)

When a text file read and write, the above three specified path with one good open function using the file name, and second operation mode, the third is coding, the path can be relative or an absolute path, the operation mode is the default r, encoding a file with the encoding parameter specifies the encoding to be consistent, otherwise it will cause reading failure.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:文件读取小例子


def main():
    file = open('README.txt', 'r', encoding='utf-8')
    print(file.read())
    file.close()


if __name__ == "__main__":
    main()

abnormal

Like the above code is likely because the file does not exist or is inconsistent coding can not be opened, then an abnormal condition causes the program to crash. So python exception mechanism to provide improved fault tolerance and robustness of our code.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:文件读取


def main():
    file = None
    try:
        file = open('README.txt', 'r', encoding='utf-8')
        print(file.read())
    except FileNotFoundError:
        print("无法打开该文件")
    except LookupError:
        print('指定了未知的编码!')
    except UnicodeDecodeError:
        print('读取文件时解码错误!')
    finally:
        file.close()


if __name__ == "__main__":
    main()

We can probably an error code that is running in a try code block in the back can be followed by a number except try to catch exceptions that may occur, last used finally to close open files, free up resources, finally block regardless of the normal procedures or abnormal will be executed, so called "always execute the code block" is used as an operation to release the resources most appropriate. You can also use the context syntax, the file is automatically released when the resource by keyword specifies the file with the context and leave the object context.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:with


def main():
    try:
        with open('README.txt', 'r', encoding='utf-8') as file:
            print(file.read())
    except FileNotFoundError:
        print("无法打开该文件")
    except LookupError:
        print('指定了未知的编码!')
    except UnicodeDecodeError:
        print('读取文件时解码错误!')


if __name__ == "__main__":
    main()

File objects have readlines, which can read the file list in rows to a container, the following code.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:with


def main():
    try:
        with open('README.txt', 'r', encoding='utf-8') as file:
            lines = file.readlines()
            print(lines[0])
    except FileNotFoundError:
        print("无法打开该文件")
    except LookupError:
        print('指定了未知的编码!')
    except UnicodeDecodeError:
        print('读取文件时解码错误!')


if __name__ == "__main__":
    main()

Can go traversed by for-in, I only index 0 is because my file is only one line.

Small Case File Copy

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:


def main():
    try:
        with open('123.png', 'rb') as file1:
            data = file1.read()
            print(data)
        with open('copy_123.png', 'wb') as file2:
            file2.write(data)
    except FileNotFoundError as e:
        print('指定的文件无法打开.')
    except IOError as e:
        print('读写文件时出现错误.')
    print('程序执行结束.')


if __name__ == "__main__":
    main()

read json

Now, as a json format to exchange data between heterogeneous systems are very popular, knowledge about the json, json can refer to the official website.

{
	"name": "zhangshan",
	"age": 12,
	"books": [
		{"name": "book1", "price": 12},
		{"name": "book2", "price": 14}
	]
}

And a dictionary of it, and python correspondence is as follows.

JSON Python
object dict
array list
string str
number (int / real) int / float
true / false True / False
null None
Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True / False true / false
None null

python json module in the following.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:json的使用
import json


def main():
    someone = {
        "name": "zhangshan",
        "age": 12,
        "books": [
            {"name": "book1", "price": 12},
            {"name": "book2", "price": 14}
        ]
    }
    try:
        with open("data.json", 'w', encoding='utf-8') as file1:
            json.dump(someone, file1)
    except IOError as e:
        print(e)
    print("数据保存完成!")


if __name__ == "__main__":
    main()

json module in four main functions:

  • dump - The Python JSON format serialized object according to a file
  • dumps - Python string object processing into JSON format
  • load - the JSON data file deserialized into objects
  • loads - The contents of the string deserialized into objects Python
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:json
import json


def main():
    temp_dict = {'name': 'zhangsan', 'age': 12, 'role': 'student'}
    json_str = json.dumps(temp_dict)
    print(json_str)
    # 因为文件存在所以就没有进行try-except
    file = open('data.json', 'r')
    temp_dict1 = json.load(file)
    print(temp_dict1['name'])
    file.close()
    

if __name__ == "__main__":
    main()

Epilogue

The fourth day also saw a lot, continue to work hard!

If you find my articles where there is an error or have any good ideas can contact me, we study together progress together, my email address is [email protected]

let’s do more of those!

Published 26 original articles · won praise 2 · Views 2345

Guess you like

Origin blog.csdn.net/qq_42909545/article/details/93708851