Python学习笔记(九)——Python _init_特殊方法和模块

本文介绍了Python中的特殊方法,包括构造方法、重写构造方法和静态方法等,并详细讲解了如何自定义及引用模块。此外,还概述了Python标准库和其他常用模块的基本概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、特殊方法

特殊方法就是形如_future_\_main_这类方法的统称。

1、特殊方法

 

#__init__构造方法
class FooBar:
    def __init__(self): #构造方法,当对象被创建后,会立刻调用构造方法
        self.somevar=42
        
f=FooBar()
print f.somevar #42

2、构造方法重写

 

两类继承:

 

#重写方法
class A:
    def hi(self):
        print "hi,A"
class B(A):
    pass

a=A()
a.hi() #hi,A
b=B()
b.hi()#hi,A

重写子类构造方法:

 

 

#开始重写
class B1(A):
    def hi(self):
        print "hi,B1"
    
b=B1()
b.hi()#hi,B1
#继承关系,如果类的构造方法被重写(子类),则初始化子类(重写的构造方法)时,要调用父类的构造方法。否则子类可能不会被正确的初始化。

3、静态方法

 

 

_meteclass_=type
class Myclass:
    @staticmethod
    def smeth():
        print "static"
    @classmethod
    def nosmeth(cls):
        print "class method of ",cls


Myclass.smeth() #static
Myclass.nosmeth() #class method of  __main__.Myclass

二、模块

 

1、自定义模块

 

#coding: utf-8

def hi():
    print "hi"

2、引用自定义模块

 

在模块2中引入刚自定义的模块,并调用hi方法

 

#coding:utf-8

import Module
Module.hi() #hi

3、python 标准库及其他常用模块

 

python提供了一套基础模块,可以简单理解成封装了一套工具类,可import后直接调用的模块集合=标准库。常用的sys、os、fileinput、sets、time、random。具体使用边查边用。

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值