1. 程式人生 > 實用技巧 >【Python基礎程式設計244 ● 模組 ● from...import...語句匯入模組】

【Python基礎程式設計244 ● 模組 ● from...import...語句匯入模組】


---------Python基礎程式設計---------

Author : AI菌


【內容講解】

# import module01 as m01
# import module02 as m02
或者
# import module01 as m01, module02 as m02

【程式碼演示】

# import module01
# import module02

# import module01 as m01
# import module02 as m02

import module01 as m01, module02 as m02

print(m01.a)
print(m01.func1(5, 6))
s1 = m01.Student("robot", 20)
print(s1)

print("----------")

print(m02.a)
print(m02.func1(5, 6))
s2 = m02.Student("rabbit", 19)
print(s2)

module01:

# 定義全域性變數
a = 100


# 定義函式
def func1(a, b):
    return a + b


# 定義類
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"name={self.name},age={self.age}"

module02:

# 定義全域性變數
a = 200


# 定義函式
def func1(a, b):
    return a - b


# 定義類
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"name={self.name},age={self.age}"

【執行結果】

【往期精彩】

▷【Python基礎程式設計196 ● 讀取檔案的4種方式】
▷【Python基礎程式設計197 ● 讀取檔案的4種方式】
▷【Python基礎程式設計198 ● 讀取檔案的4種方式】
▷【Python基礎程式設計199 ● Python怎麼讀/寫很大的檔案】
▷【Python基礎程式設計200 ● 讀取檔案的4種方式】
▷【Python基礎程式設計201 ● 讀取檔案的4種方式】
▷【Python基礎程式設計202 ● 讀取檔案的4種方式】
▷【Python基礎程式設計203 ● 讀取檔案的4種方式】

【加群交流】