OneCoder Avatar
OneCodercoderli.com · 1025 篇博文
🐍 Python

Python 与大数据

🎨 视觉封面

Python练习-面像对象基础

📅 2022-08-04·✍️ onecode·计算中...·⏱️ 4 分钟

本部分练习Python面像对象编程基础知识。练习代码如下:

Python66 行
python面像对象学习相关代码

import types

from demo.module.module import Student
import demo.module.module as im_module

# 对象类型
print(type(123))
print(type("123"))
print(type(Student("Object", 99)))
print(type(im_module.stu1))

print(type(abs) == types.BuiltinFunctionType)
print(type((x for x in range(10))) == types.GeneratorType)

print(isinstance("abc", str))
print(isinstance([1, 2, 3], (list, tuple)))

print(dir(Student))
print(dir("123"))
print(hasattr(im_module.stu1, "__init__"))
print(hasattr(im_module.stu1, "__name"))
getattr(im_module.stu1, "print_score")()


class Fruit():
    category = "one"

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


apple = Fruit("Apple")
pear = Fruit("pear")
print(getattr(apple, "name"))
pear.category = "two"
print(getattr(apple, "category"))
print(getattr(pear, "name"))
print(getattr(pear, "category"))


# 练习
# 为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:

class Student(object):
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count += 1

# 测试:
if Student.count != 0:
    print('测试失败!')
else:
    bart = Student('Bart')
    if Student.count != 1:
        print('测试失败!')
    else:
        lisa = Student('Bart')
        if Student.count != 2:
            print('测试失败!')
        else:
            print('Students:', Student.count)
            print('测试通过!')
看完题解去实战!OneCoder C++ 信奥远征闯关平台 (oi.coderli.com)
💡 OneCoder 资源指引

所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI

🤝 技术交流与答疑

欢迎加入:C++ GESP/CSP 考级答疑群(688906745) 与 Java/Python交流群(982860385),点击可直接加群。

📚

猜你想读 · 相关文章推荐

OneCoder

OneCoder

一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com

读者讨论与留言

共 0 条讨论
邮箱必填 · 支持 Markdown 格式与直接回复
💬 还没有读者留言,快来成为第一个讨论者吧!