包含python隱式函數(shù)的詞條

Python 有什么奇技淫巧

Python奇技淫巧

網(wǎng)站設(shè)計制作過程拒絕使用模板建站;使用PHP+MYSQL原生開發(fā)可交付網(wǎng)站源代碼;符合網(wǎng)站優(yōu)化排名的后臺管理系統(tǒng);成都網(wǎng)站設(shè)計、成都網(wǎng)站制作收費合理;免費進(jìn)行網(wǎng)站備案等企業(yè)網(wǎng)站建設(shè)一條龍服務(wù).我們是一家持續(xù)穩(wěn)定運營了10年的成都創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司。

當(dāng)發(fā)布python第三方package時, 并不希望代碼中所有的函數(shù)或者class可以被外部import, 在 __init__.py 中添加 __all__ 屬性,

該list中填寫可以import的類或者函數(shù)名, 可以起到限制的import的作用, 防止外部import其他函數(shù)或者類

#!/usr/bin/env python

# -*- coding: utf-8 -*-

frombaseimportAPIBase

fromclientimportClient

fromdecoratorimportinterface, export, stream

fromserverimportServer

fromstorageimportStorage

fromutilimport(LogFormatter, disable_logging_to_stderr,

enable_logging_to_kids, info)

__all__ = ['APIBase','Client','LogFormatter','Server',

'Storage','disable_logging_to_stderr','enable_logging_to_kids',

'export','info','interface','stream']

with的魔力

with語句需要支持 上下文管理協(xié)議的對象 , 上下文管理協(xié)議包含 __enter__ 和 __exit__ 兩個方法. with語句建立運行時上下文需要通過這兩個方法執(zhí)行 進(jìn)入和退出 操作.

其中 上下文表達(dá)式 是跟在with之后的表達(dá)式, 該表示大返回一個上下文管理對象

# 常見with使用場景

withopen("test.txt","r")asmy_file:# 注意, 是__enter__()方法的返回值賦值給了my_file,

forlineinmy_file:

print line

詳細(xì)原理可以查看這篇文章, 淺談 Python 的 with 語句

知道具體原理, 我們可以自定義支持上下文管理協(xié)議的類, 類中實現(xiàn) __enter__ 和 __exit__ 方法

#!/usr/bin/env python

# -*- coding: utf-8 -*-

classMyWith(object):

def__init__(self):

print"__init__ method"

def__enter__(self):

print"__enter__ method"

returnself# 返回對象給as后的變量

def__exit__(self, exc_type, exc_value, exc_traceback):

print"__exit__ method"

ifexc_tracebackisNone:

print"Exited without Exception"

returnTrue

else:

print"Exited with Exception"

returnFalse

deftest_with():

withMyWith()asmy_with:

print"running my_with"

print"------分割線-----"

withMyWith()asmy_with:

print"running before Exception"

raiseException

print"running after Exception"

if__name__ =='__main__':

test_with()

執(zhí)行結(jié)果如下:

__init__ method

__enter__ method

running my_with

__exit__ method

ExitedwithoutException

------分割線-----

__init__ method

__enter__ method

running before Exception

__exit__ method

ExitedwithException

Traceback(most recent call last):

File"bin/python", line34,inmodule

exec(compile(__file__f.read(), __file__, "exec"))

File"test_with.py", line33,inmodule

test_with()

File"test_with.py", line28,intest_with

raiseException

Exception

證明了會先執(zhí)行 __enter__ 方法, 然后調(diào)用with內(nèi)的邏輯, 最后執(zhí)行 __exit__ 做退出處理, 并且, 即使出現(xiàn)異常也能正常退出

filter的用法

相對 filter 而言, map和reduce使用的會更頻繁一些, filter 正如其名字, 按照某種規(guī)則 過濾 掉一些元素

#!/usr/bin/env python

# -*- coding: utf-8 -*-

lst = [1,2,3,4,5,6]

# 所有奇數(shù)都會返回True, 偶數(shù)會返回False被過濾掉

print filter(lambda x: x % 2!=0, lst)

#輸出結(jié)果

[1,3,5]

一行作判斷

當(dāng)條件滿足時, 返回的為等號后面的變量, 否則返回else后語句

lst = [1,2,3]

new_lst = lst[0]iflstisnotNoneelseNone

printnew_lst

# 打印結(jié)果

1

裝飾器之單例

使用裝飾器實現(xiàn)簡單的單例模式

# 單例裝飾器

defsingleton(cls):

instances = dict() # 初始為空

def_singleton(*args, **kwargs):

ifclsnotininstances:#如果不存在, 則創(chuàng)建并放入字典

instances[cls] = cls(*args, **kwargs)

returninstances[cls]

return_singleton

@singleton

classTest(object):

pass

if__name__ =='__main__':

t1 = Test()

t2 = Test()

# 兩者具有相同的地址

printt1, t2

staticmethod裝飾器

類中兩種常用的裝飾, 首先區(qū)分一下他們

普通成員函數(shù), 其中第一個隱式參數(shù)為 對象

classmethod裝飾器 , 類方法(給人感覺非常類似于OC中的類方法), 其中第一個隱式參數(shù)為 類

staticmethod裝飾器 , 沒有任何隱式參數(shù). python中的靜態(tài)方法類似與C++中的靜態(tài)方法

#!/usr/bin/env python

# -*- coding: utf-8 -*-

classA(object):

# 普通成員函數(shù)

deffoo(self, x):

print "executing foo(%s, %s)"% (self, x)

@classmethod# 使用classmethod進(jìn)行裝飾

defclass_foo(cls, x):

print "executing class_foo(%s, %s)"% (cls, x)

@staticmethod# 使用staticmethod進(jìn)行裝飾

defstatic_foo(x):

print "executing static_foo(%s)"% x

deftest_three_method():

obj = A()

# 直接調(diào)用噗通的成員方法

obj.foo("para")# 此處obj對象作為成員函數(shù)的隱式參數(shù), 就是self

obj.class_foo("para")# 此處類作為隱式參數(shù)被傳入, 就是cls

A.class_foo("para")#更直接的類方法調(diào)用

obj.static_foo("para")# 靜態(tài)方法并沒有任何隱式參數(shù), 但是要通過對象或者類進(jìn)行調(diào)用

A.static_foo("para")

if__name__=='__main__':

test_three_method()

# 函數(shù)輸出

executing foo(__main__.Aobject at0x100ba4e10, para)

executing class_foo(class'__main__.A',para)

executing class_foo(class'__main__.A',para)

executing static_foo(para)

executing static_foo(para)

property裝飾器

定義私有類屬性

將 property 與裝飾器結(jié)合實現(xiàn)屬性私有化( 更簡單安全的實現(xiàn)get和set方法 )

#python內(nèi)建函數(shù)

property(fget=None, fset=None, fdel=None, doc=None)

fget 是獲取屬性的值的函數(shù), fset 是設(shè)置屬性值的函數(shù), fdel 是刪除屬性的函數(shù), doc 是一個字符串(like a comment).從實現(xiàn)來看,這些參數(shù)都是可選的

property有三個方法 getter() , setter() 和 delete() 來指定fget, fset和fdel。 這表示以下這行

classStudent(object):

@property #相當(dāng)于property.getter(score) 或者property(score)

defscore(self):

returnself._score

@score.setter #相當(dāng)于score = property.setter(score)

defscore(self, value):

ifnotisinstance(value, int):

raiseValueError('score must be an integer!')

ifvalue 0orvalue 100:

raiseValueError('score must between 0 ~ 100!')

self._score = value

iter魔法

通過yield和 __iter__ 的結(jié)合, 我們可以把一個對象變成可迭代的

通過 __str__ 的重寫, 可以直接通過想要的形式打印對象

#!/usr/bin/env python

# -*- coding: utf-8 -*-

classTestIter(object):

def__init__(self):

self.lst = [1,2,3,4,5]

defread(self):

foreleinxrange(len(self.lst)):

yieldele

def__iter__(self):

returnself.read()

def__str__(self):

return','.join(map(str, self.lst))

__repr__ = __str__

deftest_iter():

obj = TestIter()

fornuminobj:

printnum

printobj

if__name__ =='__main__':

test_iter()

神奇partial

partial使用上很像C++中仿函數(shù)(函數(shù)對象).

在stackoverflow給出了類似與partial的運行方式

defpartial(func, *part_args):

defwrapper(*extra_args):

args = list(part_args)

args.extend(extra_args)

returnfunc(*args)

returnwrapper

利用用閉包的特性綁定預(yù)先綁定一些函數(shù)參數(shù), 返回一個可調(diào)用的變量, 直到真正的調(diào)用執(zhí)行

#!/usr/bin/env python

# -*- coding: utf-8 -*-

fromfunctoolsimportpartial

defsum(a, b):

returna + b

deftest_partial():

fun = partial(sum, 2)# 事先綁定一個參數(shù), fun成為一個只需要一個參數(shù)的可調(diào)用變量

printfun(3)# 實現(xiàn)執(zhí)行的即是sum(2, 3)

if__name__ =='__main__':

test_partial()

# 執(zhí)行結(jié)果

5

神秘eval

eval我理解為一種內(nèi)嵌的python解釋器(這種解釋可能會有偏差), 會解釋字符串為對應(yīng)的代碼并執(zhí)行, 并且將執(zhí)行結(jié)果返回

看一下下面這個例子

#!/usr/bin/env python

# -*- coding: utf-8 -*-

deftest_first():

return3

deftest_second(num):

returnnum

action = { # 可以看做是一個sandbox

"para":5,

"test_first": test_first,

"test_second": test_second

}

deftest_eavl():

condition = "para == 5 and test_second(test_first) 5"

res = eval(condition, action) # 解釋condition并根據(jù)action對應(yīng)的動作執(zhí)行

printres

if__name__ =='_

exec

exec在Python中會忽略返回值, 總是返回None, eval會返回執(zhí)行代碼或語句的返回值

exec 和 eval 在執(zhí)行代碼時, 除了返回值其他行為都相同

在傳入字符串時, 會使用 compile(source, 'string', mode) 編譯字節(jié)碼. mode的取值為 exec 和 eval

#!/usr/bin/env python

# -*- coding: utf-8 -*-

deftest_first():

print"hello"

deftest_second():

test_first()

print"second"

deftest_third():

print"third"

action = {

"test_second": test_second,

"test_third": test_third

}

deftest_exec():

exec"test_second"inaction

if__name__ =='__main__':

test_exec() # 無法看到執(zhí)行結(jié)果

getattr

getattr(object, name[, default]) Return the value of

the named attribute of object. name must be a string. If the string is

the name of one of the object’s attributes, the result is the value of

that attribute. For example, getattr(x, ‘foobar’) is equivalent to

x.foobar. If the named attribute does not exist, default is returned if

provided, otherwise AttributeError is raised.

通過string類型的name, 返回對象的name屬性(方法)對應(yīng)的值, 如果屬性不存在, 則返回默認(rèn)值, 相當(dāng)于object.name

# 使用范例

classTestGetAttr(object):

test = "test attribute"

defsay(self):

print"test method"

deftest_getattr():

my_test = TestGetAttr()

try:

printgetattr(my_test,"test")

exceptAttributeError:

print"Attribute Error!"

try:

getattr(my_test, "say")()

exceptAttributeError:# 沒有該屬性, 且沒有指定返回值的情況下

print"Method Error!"

if__name__ =='__main__':

test_getattr()

# 輸出結(jié)果

test attribute

test method

命令行處理

defprocess_command_line(argv):

"""

Return a 2-tuple: (settings object, args list).

`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.

"""

ifargvisNone:

argv = sys.argv[1:]

# initialize the parser object:

parser = optparse.OptionParser(

formatter=optparse.TitledHelpFormatter(width=78),

add_help_option=None)

# define options here:

parser.add_option( # customized description; put --help last

'-h','--help', action='help',

help='Show this help message and exit.')

settings, args = parser.parse_args(argv)

# check number of arguments, verify values, etc.:

ifargs:

parser.error('program takes no command-line arguments; '

'"%s" ignored.'% (args,))

# further process settings args if necessary

returnsettings, args

defmain(argv=None):

settings, args = process_command_line(argv)

# application code here, like:

# run(settings, args)

return0# success

if__name__ =='__main__':

status = main()

sys.exit(status)

讀寫csv文件

# 從csv中讀取文件, 基本和傳統(tǒng)文件讀取類似

importcsv

withopen('data.csv','rb')asf:

reader = csv.reader(f)

forrowinreader:

printrow

# 向csv文件寫入

importcsv

withopen('data.csv','wb')asf:

writer = csv.writer(f)

writer.writerow(['name','address','age'])# 單行寫入

data = [

( 'xiaoming ','china','10'),

( 'Lily','USA','12')]

writer.writerows(data) # 多行寫入

各種時間形式轉(zhuǎn)換

只發(fā)一張網(wǎng)上的圖, 然后差文檔就好了, 這個是記不住的

字符串格式化

一個非常好用, 很多人又不知道的功能

name ="andrew"

"my name is {name}".format(name=name)

'my name is andrew'

Python 中max( )函數(shù)與lambda隱式函數(shù)結(jié)合使用時出錯。

print max.__doc__max(iterable[, key=func]) - valuemax(a, b, c, ...[, key=func]) - valueWith a single iterable argument, return its largest item.With two or more arguments, return the largest argument. 后面的func,是比較函數(shù),條件成立后,max執(zhí)行結(jié)束。 所以: array1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] max(array1, key=lambda x: x 6) 7 如果: max([i for i in range(0,9)], key=lambda x: x = 6)6 執(zhí)行結(jié)果就是6

如何解決python2不能隱式繼承

繼承是所有開發(fā)語言的必修內(nèi)容,而本文寫的只是Python繼承中的特殊之處,關(guān)于繼承概念及內(nèi)容可以自行百度(不裝B,感覺百度挺好的)1.構(gòu)造函數(shù):

要說繼承,先要說一下構(gòu)造函數(shù)。Java要求是與類名相同并且無返回值,而Python則是強制要求命名為“__init__()”。

當(dāng)創(chuàng)建類的對象時,會自動先調(diào)用構(gòu)造函數(shù),一般用于初始化。構(gòu)造函數(shù)可以不寫,那么程序會隱式自動增加一個空的構(gòu)造函數(shù)。

2.繼承寫法:

(1).class 空格 類名稱 括號內(nèi)填寫父類名 冒號具體寫法如下class A:

def __init__(self):

pass

def print_class_name(self):

print "this is class A"

class B(A):

def __init__(self):

pass

if __name__ == "__main__":

class_b = B()

class_b.print_class_name()

上面代碼首先定義了一個名為“A”的類,包含一個名為“print_class_name”的方法。然后,定義一個名為“B”的類,繼承“A”,同時繼承了“A”類的“print_class_name”的方法。

此時“A”類為“B”類的父類或者叫基類,“B”類是“A”類的子類,子類會繼承父類的所有公共方法。

(2).意義:

一字記之曰“懶!”(感嘆號不算字)我始終相信賴人才能推動科學(xué)進(jìn)步。

言歸正傳,假如你要寫一個老王類,包含年齡、性別等方法,后面還要寫一個老王的兒子小王類,也有年齡、性別等方法?

class FatherWang:

def __init__(self, age=43, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

class SonWang:

def __init__(self, age=13, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

if __name__ == "__main__":

father = FatherWang(43, "man")

father.age()

father.sex()

son = SonWang(13, "man")

son.age()

son.sex()

你會發(fā)現(xiàn)兩個類中有相同名稱和功能的方法,這樣寫豈不是很重復(fù)很累?(盡管按鍵盤次數(shù)不算太多,我依然覺得很累)如果有繼承就很好解決了。

class FatherWang:

def __init__(self, age=43, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

class SonWang(FatherWang):

def __init__(self, age=13, sex='man'):

FatherWang.__init(age, sex)

if __name__ == "__main__":

father = FatherWang(43, "man")

father.age()

father.sex()

son = SonWang(13, "man")

son.age()

son.sex()

兩者運行結(jié)果完全一樣,但是使用繼承方法卻省了很多按鍵盤的次數(shù)。

3.經(jīng)典類與新式類:

(1)經(jīng)典類寫法:

class A:

pass

(2)新式類寫法:

class A(object):

pass

可以看出,新式類和經(jīng)典類的區(qū)別在于,是否繼承object這個基類。object是所有類的父類。所以之前不帶“(object)”的寫法,屬于經(jīng)典類寫法,加上“(object)”就是新式類的寫法。

(3).原因:這里我得吐槽一下Python的版本混亂。2.2版本之前只有經(jīng)典類寫法,這里有一個問題,代碼如下?

class A:

pass

class B(object):

pass

a = A()

b = B()

print a.__class__

print type(a)

print "----------"

print b.__class__

print type(b)

結(jié)果為:

__main__.A

type 'instance'

----------

class '__main__.B'

class '__main__.B'

首先A類為經(jīng)典類,B類為新式類。__class__屬性和type()方法都是返回對象類型,那么問題來了,使用經(jīng)典類的寫法返回結(jié)果卻不一致。因此在2.2版本之后出現(xiàn)了新式類來解決這個問題,自然,新式類和經(jīng)典類還有更大的區(qū)別在后面說。另外在3.3版本中,無論使用哪種寫法,python都會隱式的繼承object,所以3.3版本不會再有經(jīng)典類(在這里我只想問,早干什么去了!),但是鑒于3.3兼容性問題,貌似沒有太多人用。

4.方法重寫與方法重載

(1).方法重寫:

class FatherWang:

def __init__(self, age=43, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

def name(self):

print "Wang_yang"

class SonWang(FatherWang):

def __init__(self, age=13, sex='man'):

FatherWang.__init(age, sex)

def name(self):

print "Wang_xiaoming"

if __name__ == "__main__":

father = FatherWang(43, "man")

father.age()

father.sex()

father.name()

son = SonWang(13, "man")

son.age()

son.sex()

son.name()

比繼承寫法(2)中的代碼相比,兩個類分別多了同名的方法“name”,之前說過子類會繼承父類的方法,那么這時候兩個類有相同名字的方法,沖突了,怎么處理?

這個時候,就叫方法重寫??梢岳斫鉃椋宇惖摹皀ame”方法把父類的“name”方法覆蓋了,重新寫了,所以調(diào)用子類的“name”方法時,會以子類的為準(zhǔn)(盡管這種理解并不準(zhǔn)確,但是可以很好解釋“方法重寫”這個名詞,后面會講到正確理解)。

注意下面的代碼

class FatherWang:

def __init__(self, age=43, sex="man"):

self.a = age

self.s = sex

print "I am FatherWang"

def age(self):

print "Father age:"+str(self.a)

def sex(self):

print "Father sex:"+str(self.s)

class MotherLi:

def __init__(self, age=40, sex="woman"):

self.a = age

self.s = sex

print "I am MotherLi"

def age(self):

print "Mother age:"+str(self.a)

def sex(self):

print "Mother sex"+str(self.s)

class SonWang(FatherWang, MotherLi):

def __init__(self, age=13, sex="man"):

FatherWang.__init__(self, age, sex)

MotherLi.__init__(self, age, sex)

print "I am SonWang"

if __name__ == "__main__":

son = SonWang()

son.age()

son.sex()

執(zhí)行結(jié)果:

I am FatherWang

I am MotherLi

I am SonWang

Father age:13

Father sex:man

在之前代碼上稍作修改,另外增加了一個MotherLi的類,SonWang類繼承了FatherWang類和MotherLi類。注意,這是經(jīng)典類的寫法。

首先,我們知道了python多繼承的寫法,就是在括號中上一個父類后面加個逗號,然后再寫上下一個父類的名字:

class SonWang(FatherWang, MotherLi):

其次,F(xiàn)atherWang類和MotherLi類,都有名為age和sex方法,SonWang類為什么會繼承FatherWang類的方法呢?那么把SonWang類的繼承順序改一下class SonWang(MotherLi, FatherWang):

就會發(fā)現(xiàn)繼承的是MotherLi類的方法。

通過結(jié)果可知,是按照繼承的順序。

讓我們把代碼結(jié)構(gòu)變得更發(fā)雜一些吧,我想會崩潰的,哈哈哈?

class Grandfather:

def __init__(self, age=73, sex="man"):

self.a = age

self.s = sex

print "I am Grandfather"

def age(self):

print "Grandfather age:"+str(self.a)

def sex(self):

print "Grandfather sex:"+str(self.s)

def Interesting(self):

print "Grandfather Interesting"

class Grandmother:

def __init__(self, age=70, sex="woman"):

self.a = age

self.s = sex

print "I am Grandmother"

def age(self):

print "Grandmother age:"+str(self.a)

def sex(self):

print "Grandmother sex:"+str(self.s)

def Interesting(self):

print "Grandmother Interesting"

class FatherWang(Grandfather, Grandmother):

def __init__(self, age=43, sex="man"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am FatherWang"

def age(self):

print "Father age:"+str(self.a)

def sex(self):

print "Father sex:"+str(self.s)

class MotherLi(Grandfather, Grandmother):

def __init__(self, age=40, sex="woman"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am MotherLi"

def age(self):

print "Mother age:"+str(self.a)

def sex(self):

print "Mother sex"+str(self.s)

def Interesting(self):

print "MotherLi Interesting"

class SonWang(FatherWang, MotherLi):

def __init__(self, age=13, sex="man"):

FatherWang.__init__(self, age, sex)

MotherLi.__init__(self, age, sex)

print "I am SonWang"

if __name__ == "__main__":

son = SonWang()

son.age()

son.sex()

son.Interesting()

執(zhí)行結(jié)果:

I am Grandfather

I am Grandmother

I am FatherWang

I am Grandfather

I am Grandmother

I am MotherLi

I am SonWang

Father age:13

Father sex:man

Grandfather Interesting

話說,我自己都有點兒暈。簡單來講,就是兒子繼承了老爸、老媽,然后老爸繼承了爺爺、奶奶,媽媽繼承了老爺、姥姥。(真是一大家子啊)通過執(zhí)行結(jié)果可知,兒子類先找到老爸類,然后再找老爸類的第1個父類爺爺類,此時發(fā)現(xiàn)爺爺類沒有父類了,那么執(zhí)行初始化。然后還要繼續(xù)找到老爸類的第2個父類奶奶類,此時發(fā)現(xiàn)奶奶類沒有父類了,執(zhí)行初始化。此時老爸類的所有父類都初始化完成,初始化自己。然后開始找媽媽類……那么為什么Interesting方法會使用爺爺類的呢?奶奶類、老爺類、姥姥類都有???首先兒子類沒有Interesting方法,會先找第1個父類老爸類。發(fā)現(xiàn)老爸類也沒有,再找老爸類的第1個父類,發(fā)現(xiàn)找到了,那么就直接調(diào)用不再往下找了。

結(jié)論:經(jīng)典類的多繼承,按照繼承順序查找。即,從左到右,從下到上的方式。注意,只有經(jīng)典類是這樣的!

(2).新式類的多繼承:

class Grandfather(object):

def __init__(self, age=73, sex="man"):

self.a = age

self.s = sex

print "I am Grandfather"

def age(self):

print "Grandfather age:"+str(self.a)

def sex(self):

print "Grandfather sex:"+str(self.s)

def Interesting(self):

print "Grandfather Interesting"

class Grandmother(object):

def __init__(self, age=70, sex="woman"):

self.a = age

self.s = sex

print "I am Grandmother"

def age(self):

print "Grandmother age:"+str(self.a)

def sex(self):

print "Grandmother sex:"+str(self.s)

def Interesting(self):

print "Grandmother Interesting"

class FatherWang(Grandfather, Grandmother):

def __init__(self, age=43, sex="man"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am FatherWang"

def age(self):

print "Father age:"+str(self.a)

def sex(self):

print "Father sex:"+str(self.s)

class MotherLi(Grandfather, Grandmother):

def __init__(self, age=40, sex="woman"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am MotherLi"

def age(self):

print "Mother age:"+str(self.a)

def sex(self):

print "Mother sex"+str(self.s)

def Interesting(self):

print "MotherLi Interesting"

class SonWang(FatherWang, MotherLi):

def __init__(self, age=13, sex="man"):

FatherWang.__init__(self, age, sex)

MotherLi.__init__(self, age, sex)

print "I am SonWang"

if __name__ == "__main__":

son = SonWang()

son.age()

son.sex()

son.Interesting()

執(zhí)行結(jié)果:

I am Grandfather

I am Grandmother

I am FatherWang

I am Grandfather

I am Grandmother

I am MotherLi

I am SonWang

Father age:13

Father sex:man

MotherLi Interesting

python中的if not 怎么用

python中的if not的用法說明如下:

1、if的語法為:if 條件為真:執(zhí)行語句,而not是取反的意思。

2、從上面的解釋可理解為:if not 條件為真:執(zhí)行語句==if 條件不為真:執(zhí)行語句。

3、舉例:if n3:print "True",假如n=3,就打印“True”。如果加上not,即為if not n3:print “True”,就有:n=3,才會打印“True"。

擴(kuò)展資料:

python中的“if not 1”:

if條件語句后面需要跟隨bool類型的數(shù)據(jù),即True或者False。然而,如果不是bool類型的數(shù)據(jù),可以將其轉(zhuǎn)換成bool類型的數(shù)據(jù),轉(zhuǎn)換的過程是隱式的。

在Python中,None、空列表[]、空字典{}、空元組()、0等一系列代表空和無的對象會被轉(zhuǎn)換成False。除此之外的其它對象都會被轉(zhuǎn)化成True。

在命令“if not 1”中,1便會轉(zhuǎn)換為bool類型的True。not是邏輯運算符非,not 1則恒為False。因此if語句if not 1之下的語句,永遠(yuǎn)不會執(zhí)行。

python 怎么樣隱式函數(shù)調(diào)用

最常用的是在類定義的方法,給一個property的裝飾器,可以安裝調(diào)用屬性的方式調(diào)用

網(wǎng)站標(biāo)題:包含python隱式函數(shù)的詞條
文章URL:http://muchs.cn/article40/hgejho.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)云服務(wù)器、面包屑導(dǎo)航、全網(wǎng)營銷推廣品牌網(wǎng)站設(shè)計、域名注冊

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)