類的私有屬性以及內建方法(一)

2021-08-18 02:01:16 字數 3951 閱讀 2991

class people:

_country='china'#私有屬性,仍然可以通過._country訪問

__language='chinese'#私有屬性,不可以通過.__language訪問,可以通過_people__language訪問

def __init__(self,name,age,gender):

self.name=name

self._gender=gender

self.__age=age

def _test(self):

print('this is test')

def __test(self):

print('this is test2')

print(people.__dict__)#可以看到python對類的雙下劃線私有屬性和方法進行了重新命名

print(people._country)

#print(people.__language)會報錯

print(people._people__language)

p=people('alex',18,'male')

print(p.__dict__)#可以看到python對例項的雙下劃線私有屬性和方法進行了重新命名

print(p.name,p._gender,p._people__age)

p._test()

p._people__test()

雖然私有變數與方法都可以通過一定方式訪問到,但是不推薦去訪問這些值

class people:

_country='china'#私有屬性,仍然可以通過._country訪問

__language='chinese'#私有屬性,不可以通過.__language訪問,可以通過_people__language訪問

def __init__(self,name,age,gender):

self.name=name

self._gender=gender

self.__age=age

def _test(self):

print('this is test')

def __test(self):

print('this is test2')

p=people('alex',18,'male')

#檢視類或者例項是否有給定的屬性或者方法,返回true或者false

print(hasattr(people,'_test'))

print(hasattr(p,'__age'))

#獲取類或例項的屬性或者方法的值,當屬性或方法不存在時,返回輸入的第三引數,預設是none

print(getattr(people,'_country'))

print(getattr(p,'__age',0))

#給類或例項新增屬性或者方法

setattr(people,'func',lambda x:x+1)

print(people.func(10))

setattr(people,'skin','yello')

print(people.skin)

setattr(p,'salary',10000)

print(p.salary)

print(people.__dict__)

print(p.__dict__)

#刪除類或例項的屬性或者方法

delattr(p,'salary')

delattr(people,'_test')

print('-'*20)

print(people.__dict__)

print(p.__dict__)

其實反射中的四種方法是呼叫類內建的attr方法。例如呼叫getattr()其實在呼叫類中內建的__getattr__().

呼叫getattr(obj,name)若name屬性已存在則不會呼叫__getattr__方法,當輸入的屬性不存在時才會呼叫.通過自定義__getattr__函式可以說明

def __init__(self,name,age,gender):

self.name=name

self._gender=gender

self.__age=age

def _test(self):

print('this is test')

def __test(self):

print('this is test2')

def __getattr__(self, item):

print('執行__getattr__,屬性%s不存在'%item)

p=people('alex',18,'ale')

p.name

p.age

呼叫setattr()時立即呼叫__setattr__函式,特別是例項化時其實就是呼叫__setattr__

class people:

_country='china'#私有屬性,仍然可以通過._country訪問

__language='chinese'#私有屬性,不可以通過.__language訪問,可以通過_people__language訪問

def __init__(self,name,age,gender):

self.name=name

self._gender=gender

self.__age=age

def _test(self):

print('this is test')

def __test(self):

print('this is test2')

def __getattr__(self, item):

print('執行__getattr__,屬性%s不存在'%item)

def __setattr__(self, key, value):

print('設定屬性%s:%s'%(key,value))

p=people('alex',18,'ale')

p.name#其實並沒有設定,只是列印出來了,所以屬性不存在

p.age

呼叫hasattr(),delattr()時一樣會立即執行__hasattr__,__delattr__函式

import time

class filehandler:

def __init__(self,filename,model='w+',encoding='utf-8'):

self.file=open(filename,model,encoding=encoding)

self.model=model

self.encoding=encoding

def write(self,line):

if self.model=='r':

print('請轉換到寫入模式')

elif not isinstance(line,str):

print('請輸入字串')

else:

line=time.strftime('%y-%m-%d %x')+' '+line

self.file.write(line)

def __getattr__(self, item):

return getattr(self.file,item)

f1=filehandler('a.txt','a')

f1.write(123456)

f1.write('123456\n')

time.sleep(1)

f1.write('hello world\n')

time.sleep(1)

f1.write('111111')

f1.writelines(['人生苦短',',','我用python'])

# print(f1.read())

類屬性類方法,私有屬性私有方法

類屬性類方法 類屬性 使用賦值語句在class關鍵字下定義 類方法 在類內部可以直接訪問雷屬性或者其它類方法 class student objict count 0 definit self,name self.name name student.count 1 classmethod def s...

類的私有屬性和私有方法

class role def init self,name,role,weapon,value 100,money 1500 建構函式 self.name name 例項變數 靜態屬性 作用域就是實力本身 self.role role self.weapon weapon self.value va...

Python 類的私有屬性和私有方法

xx 公有變數 xx 公有變數或方法,不能通過import匯入其他模組 只有模組內部使用 類物件和子類可以訪問 xx 私有變數或方法 偽私有 類外部不能直接訪問。xx 公有變數或方法,子類可以訪問。魔法方法或屬性 例如 init 不推薦這樣命名。xx 公有變數或方法。一般為了避免和python關鍵字...