首页 > 编程 > Python > 正文

python模块和对象

2019-11-11 06:03:29
字体:
来源:转载
供稿:网友

模块导入

python的模块相当于java中的包

import 包名.模块名import 包名.模块名 as 新模块名forom 包名 import 模块名forom 包名 import 模块名 as 新模块名

动态导入模块

python2.7/2.6提供了json模块,但是python2.5没有提供,这时候要想使用json模块就需要try...except...确保导入模块,类似于javatry ... catch...

try: import jsonexcept ImportError: import simplejson as json PRint json.dumps({'python':2.7})

future功能

旧版本想使用新的版本才有的功能可以使用该方法

例如:

在Python 3.x中,字符串统一为unicode,不需要加前缀 u,而以字节存储的str则必须加前缀 b。请利用future的unicode_literals在Python 2.7中编写unicode字符串

from __future__ import unicode_literalss = 'am I an unicode?'print isinstance(s, unicode)

安装第三方模块

pip install [第三方模块名]安装成功之后导入即刻import [第三方模块名]

python的对象

初始化函数

注意__init__(self,**kw)中的self相当于javathis

class Person(object): # 初始化函数,类似于构造函数,**kw表示一个dict(key,value) def __init__(self, name, gender, birth, **kw): self.name = name self.gender = gender self.birth = birth self.__dict__.update(kw)xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student')print xiaoming.nameprint xiaoming.job# 输出# Xiao Ming# Student

类的属性

#-*- coding:utf-8 -*-class Person(object): # 静态私有成员 __count=0 # 静态方法 @classmethod def how_many(cls): return cls.__count # 初始化方法 def __init__(self,name,score): self.name=name # 私有成员 self.__score=score Person.__count=Person.__count+1 # 返回私有成员的方法 def get_score(self): return self.__scoreprint Person.how_many()p1=Person('Bart',90)p1=Person('Lisa',95)p1=Person('Maggie',96)print Person.how_many()print p1.get_score()print p1.get_score()print p1.get_score()# 输出:# 0# 3# 96# 96# 96

类的继承

# -*- coding:utf-8 -*-class Person(object): # 初始化函数 def __init__(self,name,gender): self.name=name self.gender=gender # 类似java的toString方法 def __str__(self): return '(Person:%s %s)'%(self.name,self.gender) # 直接输入对象并打印,面向开发者 __repr__=__str__class Play(object): def __init__(self,name): self.name=name def do(self): return '%s...play..'%(self.name)# 继承两个类 class Student(Person,Play): def __init__(self,name,gender,score,**kw): super(Student,self).__init__(name,gender) self.score=score self.__dict__.update(kw) def __str__(self): return '(Student:%s %s %s)'%(self.name,self.gender,self.score) __repr__=__str__ # 重写了父类的do()方法 def do(self): return 'Student...do()...'p1 = Person('bart','man')print p1s1 = Student('lisa','women',98)print s1print s1.do()# 父类转化为子类s2 = Person('maggie','women')print s2

输出:

(Person:bart man)(Student:lisa women 98)Student...do()...(Person:maggie women)

@property

当给对象赋值时候

class Student(object): def __init__(self, name, score): self.name = name self.score = score

当我们想要修改一个 Studentscroe 属性时,可以这么写:

s = Student('Bob', 59) s.score = 60 但是也可以这么写:

s.score = 1000 显然,直接给属性赋值无法检查分数的有效性。

如果利用两个方法:

class Student(object): def __init__(self, name, score): self.name = name self.__score = score def get_score(self): return self.__score def set_score(self, score): if score < 0 or score > 100: raise ValueError('invalid score') self.__score = score

这样一来,s.set_score(1000) 就会报错。

这种使用 get/set方法来封装对一个属性的访问在许多面向对象编程的语言中都很常见。

但是写 s.get_score()s.set_score() 没有直接写 s.score 来得直接。

有没有两全其美的方法?—-有。

因为Python支持高阶函数,在函数式编程中我们介绍了装饰器函数,可以用装饰器函数把 get/set 方法“装饰”成属性调用:

class Student(object): def __init__(self, name, score): self.name = name self.__score = score @property def score(self): return self.__score @score.setter def score(self, score): if score < 0 or score > 100: raise ValueError('invalid score') self.__score = scores = Student('Bob', 59)s.score = 60print s.scores.score = 1000print s.score

注意: 第一个score(self)是get方法,用@property装饰,第二个score(self, score)是set方法,用@score.setter装饰,@score.setter是前一个@property装饰后的副产品

现在,就可以像使用属性一样设置score了:

>>> s = Student('Bob', 59)>>> s.score = 60>>> print s.score60>>> s.score = 1000Traceback (most recent call last): ...ValueError: invalid score

说明对 score 赋值实际调用的是 set方法。

slots

由于Python是动态语言,任何实例在运行期都可以动态地添加属性。 如果要限制添加的属性,例如,Student类只允许添加 namegenderscore 这3个属性,就可以利用Python的一个特殊的__slots__来实现。

顾名思义,_slots_是指一个类允许的属性列表:

class Student(object): __slots__ = ('name', 'gender', 'score') def __init__(self, name, gender, score): self.name = name self.gender = gender self.score = score

现在,对实例进行操作:

>>> s = Student('Bob', 'male', 59)>>> s.name = 'Tim' # OK>>> s.score = 99 # OK>>> s.grade = 'A'Traceback (most recent call last): ...AttributeError: 'Student' object has no attribute 'grade'

__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。

call

在Python中,函数其实是一个对象:

>>> f = abs>>> f.__name__'abs'>>> f(-123)123

由于 f 可以被调用,所以,f 被称为可调用对象。

所有的函数都是可调用对象。

一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法call()。

我们把 Person 类变成一个可调用对象:

class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender def __call__(self, friend): print 'My name is %s...' % self.name print 'My friend is %s...' % friend

现在可以对 Person 实例直接调用:

>>> p = Person('Bob', 'male')>>> p('Tim')My name is Bob...My friend is Tim...

单看 p(‘Tim’) 你无法确定 p 是一个函数还是一个类实例,所以,在Python中,函数也是对象,对象和函数的区别并不显著。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表