您的位置:首页 > 编程语言 > Python开发

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

2017-03-06 17:13 886 查看
一、特殊方法

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

1、特殊方法

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

f=FooBar()
print f.somevar #422、构造方法重写
两类继承:

#重写方法
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() #hi3、python 标准库及其他常用模块
python提供了一套基础模块,可以简单理解成封装了一套工具类,可import后直接调用的模块集合=标准库。常用的sys、os、fileinput、sets、time、random。具体使用边查边用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: