国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python模塊和對象

2019-11-11 05:25:28
字體:
來源:轉載
供稿:網友

模塊導入

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中,函數也是對象,對象和函數的區別并不顯著。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 扬中市| 浠水县| 青冈县| 平昌县| 青铜峡市| 巴彦淖尔市| 讷河市| 阿瓦提县| 平武县| 兴宁市| 渭南市| 天津市| 土默特左旗| 遵义市| 宜兰县| 萨迦县| 祁阳县| 乐安县| 淮滨县| 昆山市| 乐都县| 神农架林区| 和政县| 锦州市| 遵义市| 多伦县| 峨眉山市| 阿坝| 江源县| 东方市| 毕节市| 民权县| 静安区| 兴和县| 突泉县| 越西县| 花莲市| 民勤县| 农安县| 南阳市| 图木舒克市|