python之函式用法 setattr

2021-09-07 03:33:13 字數 1076 閱讀 1457

#

-*- coding: utf-8 -*-

#python 27

#xiaodeng

#python之函式用法__setattr__

##用__setattr__函式重構方法

class

fruit():

def__init__

(self,color,price):

self.

__color =color

self.

__price =price

def__setattr__(self,name,value):#

重構方法__setattr__方法,沒有該方法會預設存在該方法

self.__dict__[name] = str('

xiaodeng,

')+str(value) #為了看出區別,特意在__setattr__方法中加了str('xiaodeng')

if__name__ == "

__main__":

fruit = fruit("

blue

", 10)

print fruit #

__main__.fruit instance

print fruit.__dict__

#print fruit.__dict__.get("

_fruit__price

") #

xiaodeng,10

#給_fruit__price設定新的屬性

fruit.__dict__["

_fruit__color

"] = '

red'

print fruit.__dict__.get("

_fruit__color

") #

red#

增加新的屬性和屬性值

fruit.__dict__['

name

']='

xiaodeng

'print fruit.__dict__

#

python之函式用法getattr

coding utf 8 python 27 xiaodeng python之函式用法getattr getattr 說明 getattr getattr object,name default value default 預設值 get a named attribute from an obje...

python之函式用法startswith

coding utf 8 python 27 xiaodeng python之函式用法startswith startswith 說明 返回布林值,用於檢查字串是否是以指定子字串開頭,如果是則返回 true,否則返回 false。startswith s.startswith prefix star...

python之函式用法vars

vars 說明 返回物件object的屬性和屬性值的字典物件 vars vars object dictionary dictionary 字典物件 without arguments,equivalent to locals with an argument,equivalent to objec...