杨桃的Python基础教程——第8章:Python类和对象(七)导入外部模块

本人CSDN博客专栏:https://blog.csdn.net/yty_7
Github地址:https://github.com/yot777/Python-Primary-Learning

 

8.9 导入外部模块

模块(module):用来从逻辑(实现一个功能)上组织的Python代码(变量、函数、类),本质就是*.py文件。

包(package):定义了一个由模块和子包组成的Python应用程序执行环境,本质就是一个有层次的文件目录结构。

 

import的作用是将外部的Python模块或包导入程序。常用于导入外部第三方已开发好的模块。

语法如下:

# 导入一个模块

import model_name

# 导入多个模块

import module_name1,module_name2

# 导入模块中的指定的属性、方法(不加括号)、类

 from module_name import module_element [as new_name]

 

注意PythonJavaimport区别:

Pythonimport模块的时候,是执行了模块的所有代码,包括生成了实例化对象。

Javaimport类的时候,并不执行类代码,也不把类加载进内存。

 

Python导入外部对象举例

#Base_A.py文件如下:
class Base:
    def __init__(self):
        print('This is Base init function')
#A单继承自Base类
class A(Base):
    def __init__(self):
        Base.__init__(self)
    def printA(self):
        print('This is init function of A')
#实例化A的对象a
a=A()
a.printA()

#B.py文件如下:
import Base_A

class B:
    def printB(self):
        print('This is init function of B')

#实例化B的对象b
b=B()
b.printB()

B.py的运行结果:
This is Base init function
This is init function of A
This is init function of B
(B.py在运行的时候直接将Base_A.py也运行了)

Java导入外部对象举例:

Java程序结构图

//Base.java
package com.yty.test5;

public class Base {
  public void Base(){
    System.out.println("This is Base init function");
  }
}


//A.java
package com.yty.test5;

public class A extends Base{
  public void A() {
    //调用父类Base的构造函数
    super.Base();
    System.out.println("This is init function of A");
  }
}


//B.java
package com.yty.test6;

import com.yty.test5.A;

public class B {
  public void B(){
    System.out.println("This is init function of B");      
  }
  public static void main(String[] args) {
    //导入了A类之后,必须实例化一个A类的对象a,才能调用A类的方法
    A a = new A();
    a.A();
    B b = new B();
    b.B();
  }
}

B.java的运行结果:
This is Base init function
This is init function of A
This is init function of B

参考教程:

廖雪峰的Python教程

https://www.liaoxuefeng.com/wiki/1016959663602400

廖雪峰的Java教程

https://www.liaoxuefeng.com/wiki/1252599548343744

Python3 教程 | 菜鸟教程
https://www.runoob.com/python3/
 

如果您觉得本篇本章对您有所帮助,欢迎关注、评论、点赞!Github欢迎您的Follow、Star!
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值