MST

星途 面试题库

面试题:Python模块中多类存储技巧之基础应用

在Python模块中,假设有类A、类B和类C,且每个类都有一些实例变量和方法。请描述如何将这些类合理地存储在模块中,以便于其他模块导入和使用,同时要考虑到代码的可读性和维护性。请用代码示例说明。
32.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 模块文件结构
    • 创建一个Python文件,例如 my_classes.py,用于存放这些类。这样将相关类集中在一个文件,提高代码的组织性。
  2. 代码示例
class A:
    def __init__(self):
        self.instance_variable_a = "Value of A"

    def method_a(self):
        return f"This is method_a from class A, with variable: {self.instance_variable_a}"


class B:
    def __init__(self):
        self.instance_variable_b = "Value of B"

    def method_b(self):
        return f"This is method_b from class B, with variable: {self.instance_variable_b}"


class C:
    def __init__(self):
        self.instance_variable_c = "Value of C"

    def method_c(self):
        return f"This is method_c from class C, with variable: {self.instance_variable_c}"
  1. 其他模块导入使用
    • 在其他Python文件中,可以使用 import 语句导入这些类并使用。
from my_classes import A, B, C

a = A()
print(a.method_a())

b = B()
print(b.method_b())

c = C()
print(c.method_c())

这样做的好处是: - 代码结构清晰,每个类的定义集中在一个模块文件,便于查找和维护。 - 导入时明确知道从哪个模块导入哪些类,提高了代码的可读性。