【Python】“笨办法”学python习题41-面向对象术语的练习

使用以下代码会无限输出类似于:
1.class X(Y):创建一个叫X的类,它是Y的一种
2.class X(object):def init(self,J):类X有一个__init__,它接收self和J作为参数
3.class X(object):def M(self,J):类X有一个名M的函数,它接收self和J作为参数
4.foo = X():将foo设为类X的一个实例
5.foo.M(J):从foo中找到M函数,并使用self和J参数调用它
6.foo.K = Q:从foo中获取K属性,并将其设为Q
来帮助你更好地认识类、对象、实例、属性

测试代码

import random
from urllib.request import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
    "class %%%(%%%):":
      "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef __init__(self, ***)" :
      "class %%% has-a __init__ that takes self and *** parameters.",
    "class %%%(object):\n\tdef ***(self, @@@)" :
      "class %%% has-a function named *** that takes self and @@@ parameters.",
    "*** = %%%()":
      "Set *** to an instance of class %%%.",
    "***.***(@@@)":
      "From *** get the *** function, and call it with parameters self, @@@.",
    "***.*** = '***'":
      "From *** get the *** attribute and set it to '***'."
}

# do they want to drill phrases first
#sys.argv是一个包含命令行参数的列表
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASES_FIRST = True
else:
    PHRASES_FIRST = False

#从链接中获取单词并填充进WORDS列表
for word in urlopen(WORD_URL).readlines():
    WORDS.append(str(word.strip(), encoding = "utf-8"))

#count()函数用来统计指定元素在目标对象中出现的次数
#random.sample(population, k)
#population表示要从中进行抽样的序列,可以是一个列表、元组或集合等可迭代对象
#k表示要抽取的样本数量,必须是一个非负整数且不大于population的长度
#最终返回一个新的列表,包含了随机抽取的k个元素。
def convert(snippet, phrase):
    #capitalize()将字符串的第一个字符转换为大写字母,并将所有其他字符(如果有的话)转换为小写
    #此处对抽到的单词进行这类处理
    class_names = [w.capitalize() for w in
                   random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    #random.randint(a, b)
    #表示闭区间[a,b],生成一个位于闭区间内的随机整数,返回值为生成的随机整数
    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        #[:]对列表中所有元素进行切片操作
        #这是python中复制列表的方法
        result = sentence[:]

        #str.replace(old, new [, count])中括号中的内容可以没有
        #用一个新字符或字符串替换字符串中某个字符串中的原有的字符或子串
        #指定 count后,只有str中前count个旧字符串old被替换
        for word in class_names:
            result = result.replace("%%%", word, 1)

        for word in other_names:
            result = result.replace("***", word, 1)

        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

# keep going until they answer "yes"
try:
  while True:
    snippets = list(PHRASES.keys())
    #用于将一个列表中的元素打乱顺序,不会生成新的列表
    random.shuffle(snippets)

    #遍历列表snippets中的每个元素并赋给snippet
    for snippet in snippets:
        phrase = PHRASES[snippet]
        question, answer = convert(snippet, phrase)
        if PHRASES_FIRST:
            question, answer = answer, question

        print(question)

        input(">")
        print(f"ANSWER: {answer}\n\n")
except EOFError:
  print("\nBye")

运行结果
可以在>后输出answer的结果,通过直接运行的练习了解各个概念。
balance、cart等单词仅作为类名、属性名、参数名等

PS D:\pystudy> & D:/anaconda3/python.exe d:/pystudy/oop_test.py english
class Balance has-a __init__ that takes self and cart parameters.
>
ANSWER: class Balance(object):
        def __init__(self, cart)


From cart get the branch attribute and set it to 'drawer'.
>
ANSWER: cart.branch = 'drawer'

相关推荐

  1. python面向对象练习

    2024-02-20 17:16:03       43 阅读
  2. python面向对象练习

    2024-02-20 17:16:03       42 阅读
  3. Python基础:【习题系列】面向对象

    2024-02-20 17:16:03       35 阅读
  4. python面向对象

    2024-02-20 17:16:03       33 阅读
  5. 零基础Python面向对象

    2024-02-20 17:16:03       43 阅读
  6. python面向对象编程

    2024-02-20 17:16:03       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-20 17:16:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-20 17:16:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-20 17:16:03       82 阅读
  4. Python语言-面向对象

    2024-02-20 17:16:03       91 阅读

热门阅读

  1. C#系列-Dapper.Contrib.Extensions应用实例(41)

    2024-02-20 17:16:03       49 阅读
  2. 【学习记录25】学习一些比较有用的git命令

    2024-02-20 17:16:03       52 阅读
  3. 【软件设计模式之适配器模式】

    2024-02-20 17:16:03       41 阅读
  4. docker (八)-docker compose容器编排

    2024-02-20 17:16:03       53 阅读
  5. 博客摘录「 Python面试宝典」2024年2月20日

    2024-02-20 17:16:03       45 阅读
  6. 浅谈分布式光伏电站运维平台在石化行业的应用

    2024-02-20 17:16:03       47 阅读
  7. qt命令行编译项目

    2024-02-20 17:16:03       46 阅读
  8. Python | Conda常用命令

    2024-02-20 17:16:03       44 阅读
  9. docker搭建现成的靶场

    2024-02-20 17:16:03       46 阅读
  10. docker 使用运行指令讲解

    2024-02-20 17:16:03       48 阅读
  11. 制作一个简单的html网页

    2024-02-20 17:16:03       50 阅读