Python study notes eight: complete object-oriented programming

我之前也写了一篇关于面向对象编程的博客,两篇博客内容相近,包含了我这两次学习的全部内容

First blog

1. Escape characters

  • \n: Newline
  • \t: Tab character, tab
  • "\" can be followed by octal or hexadecimal to represent characters, such as \141, \x61 for a
  • "\" can be followed by Unicode character encoding to represent characters
  • If you don’t want "\" to indicate escape, you can precede it with r, such as r\

2. Format

  • Method 1: Use "%"
  • Method 2: Use format
  • Method 3: Add the letter f in front of the string
a, b = 5, 10

# 方法1:
print('%d * %d = %d' % (a, b, a * b))

# 方法2:
print('{0} * {1} = {2}'.format(a, b, a * b))

# 方法3:
print(f'{a} * {b} = {a * b}')    # 适用于python 3.6以后的版本

3. Object Oriented Programming

  • For object-oriented, I think everyone is familiar with it, but how do you briefly summarize what is object-oriented? This is a very interesting question. I have studied programming languages ​​such as c language, c#, java, etc., but the interpretation of object-oriented is still not very clear. This is a question that has been bothering me. What is object-oriented?

  • "Compose a set of data structures and methods to process them into objects, group objects with the same behavior into classes, hide internal details through class encapsulation, and realize class specialization through inheritance. (Specialization) and generalization (generalization), through polymorphism (polymorphism) to achieve dynamic allocation based on object types. "Such an explanation may not be easy to understand

  • But today I saw an explanation, which may be easier to understand:
    Know the picture

4. Classes and Objects

  • Simply put, a class is a blueprint and template of an object, and an object is an instance of a class.
  • Although this explanation is a bit like using concepts to explain concepts, we can at least see from this sentence
    • Classes are abstract concepts, and objects are concrete things.
  • In the world of object-oriented programming, everything is an object. Objects have attributes and behaviors. Each object is unique and must belong to a certain class (type).
  • When we extract the static characteristics (attributes) and dynamic characteristics (behaviors) of a large number of objects with common characteristics, we can define something called a "class".

5. Define the class

  • class keyword
  • Among them, the functions written in the class are usually called (object) methods. These methods are the messages that the object can receive
class Student(object):

    # __init__是一个特殊方法用于在创建对象时进行初始化操作
    # 通过这个方法我们可以为学生对象绑定name和age两个属性
    def __init__(self, name, age):
        self.name = name
        self.age = age

        
    def study(self, courseName):
        print('%s正在学习%s.' % (self.name, courseName))

        
    # PEP 8要求标识符的名字用全小写多个单词用下划线连接
    # 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)
    def watchMovie(self):
        if self.age < 12:
            print('%s观看《喜羊羊》.' % self.name)
        else:
            print('%s快去学校上课.' % self.name)
            

6. Create and use objects

  • After defining a class, you can create an object in the following way and send a message to the object
def main():
    # 创建学生对象并指定姓名和年龄
    stu1 = Student('amy', 21)
    # 给对象发study消息
    stu1.study('Python')
    # 给对象发watchMovie消息
    stu1.watchMovie()
    stu2 = Student('李小白', 15)
    stu2.study('高等数学')
    stu2.watchMovie()


if __name__ == '__main__':
    main()

7. Access visibility issues

  • In Python, there are only two types of access permissions for attributes and methods, that is, public and private. If you want the attribute to be private, you can use two underscores as the beginning when naming the attribute
class Test:

    def __init__(self, name):
        self.__name = Jackson

    def __bar(self):
        print(self.__name)
        print('__age')


def main():
    test = Test('hello')
    test.__age()       # AttributeError: 'Test' object has no attribute '__age'
    print(test.__name) # AttributeError: 'Test' object has no attribute '__name'


if __name__ == "__main__":
    main()

Case 1: Design a function to generate a verification code of a specified length, the verification code is composed of uppercase and lowercase letters and numbers

import random


def generateCode(codeLen=4):
    """
    生成指定长度的验证码

    :param codeLen: 验证码的长度(默认4个字符)

    :return: 由大小写英文字母和数字构成的随机验证码
    """
    allChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    lastPos = len(allChars) - 1   # 生成allChars的长度,应为:61
    code = ''                     # 以空格隔开
    for _ in range(codeLen):
        index = random.randint(0, lastPos)
        code += allChars[index]
    return code

Case 2: Printing Yanghui Triangle

def main():
    num = int(input('请输入行数为: '))
    yh = [[]] * num
    for row in range(len(yh)):
        yh[row] = [None] * (row + 1)
        for col in range(len(yh[row])):
            if col == 0 or col == row:
                yh[row][col] = 1
            else:
                yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
            print(yh[row][col], end='\t')
        print()


if __name__ == '__main__':
    main()

Case 3: Two-color ball number selection

  • This example involves relatively professional knowledge. I didn't understand it. I hope that readers can tell me what you think after reading it.
from random import randrange, randint, sample


def display(balls):
    """
    输出列表中的双色球号码
    """
    for index, ball in enumerate(balls):
        if index == len(balls) - 1:
            print('|', end=' ')
        print('%02d' % ball, end=' ')
    print()


def random_select():
    """
    随机选择一组号码
    """
    red_balls = [x for x in range(1, 34)]
    selected_balls = []
    selected_balls = sample(red_balls, 6)
    selected_balls.sort()
    selected_balls.append(randint(1, 16))
    return selected_balls


def main():
    n = int(input('机选几注: '))
    for _ in range(n):
        display(random_select())


if __name__ == '__main__':
    main()

Comprehensive case 1: Define a class to describe the digital clock with automatic timekeeping

from time import sleep


class Clock(object):
    """数字时钟"""

    def __init__(self, hour=0, minute=0, second=0):
        """初始化方法

        :param hour: 时
        :param minute: 分
        :param second: 秒
        """
        self._hour = hour
        self._minute = minute
        self._second = second

    def run(self):
        """走字"""
        self._second += 1
        if self._second == 60:
            self._second = 0
            self._minute += 1
            if self._minute == 60:
                self._minute = 0
                self._hour += 1
                if self._hour == 24:
                    self._hour = 0

    def show(self):
        """显示时间"""
        return ('%02d:%02d:%02d' % (self._hour, self._minute, self._second))

def main():
    clock = Clock(12, 00, 00)
    while True:
        print(clock.show())
        sleep(1)
        clock.run()


if __name__ == '__main__':
    main()

Guess you like

Origin blog.csdn.net/amyniez/article/details/104557045