Python3.6簡單反射操作示例
本文實例講述了Python3.6簡單反射操作。分享給大家供大家參考,具體如下:
# -*- coding:utf-8 -*-
#!python3
# -----------------------
# __Author : tyran
# __Date : 17-11-13
# -----------------------
class Base:
def __init__(self):
self.name = 'aaa'
self.age = 18
def show(self):
print(self.age)
# 通過getattr()找到對象的成員
base = Base()
v = getattr(base, 'name')
print(v) # aaa
func1 = getattr(base, 'show')
func1() # 18
# 通過hasattr()查找成員是否存在
print(hasattr(base, 'name')) # True
print(hasattr(base, 'name1')) # False
# 通過setattr()給對象添加成員
setattr(base, 'k1', 'v1')
print(base.k1)
delattr(base, 'k1') # v1
# print(base.k1) 報錯AttributeError: 'Base' object has no attribute 'k1'
# -------------------------------------------------------------------------
# Class也是一個對象
class ClassBase:
sex = 'male'
def __init__(self):
self.name = 'aaa'
self.age = 11
@staticmethod
def show():
print('I am static')
@classmethod
def c_method(cls):
print(cls.sex)
sex_value = getattr(ClassBase, 'sex')
print(sex_value)
s_func = getattr(ClassBase, 'show')
s_func()
c_func = getattr(ClassBase, 'c_method')
c_func()
# 這些都沒問題
setattr(ClassBase, 'has_girlfriend', True) # 添加靜態(tài)成員
print(ClassBase.has_girlfriend) # True
# ---------------同理,模塊也是對象-------------
# 我新建了一個模塊s1.py,我把內(nèi)容復(fù)制下來
# class S1:
# def __init__(self):
# self.name = 'aaa'
# self.age = 22
#
# def show(self):
# print(self.name)
# print(self.age)
#
#
# def func1():
# print('page1')
#
#
# def func2():
# print('page2')
# 一個類,兩函數(shù)
import s1
s1_class = getattr(s1, 'S1', None)
if s1_class is not None:
c1 = s1_class()
c1.show()
# aaa
# 22
getattr(s1, 'func1')() # page1
f2 = 'func2'
if hasattr(s1, f2):
getattr(s1, 'func2')() # page2
注釋中說明的s1.py如下:
# -*- coding:utf-8 -*-
#!python3
class S1:
def __init__(self):
self.name = 'aaa'
self.age = 22
def show(self):
print(self.name)
print(self.age)
def func1():
print('page1')
def func2():
print('page2')
# 一個類,兩函數(shù)
程序運行結(jié)果:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python函數(shù)式編程模塊functools的使用與實踐
本文主要介紹了Python函數(shù)式編程模塊functools的使用與實踐,教你如何使用?functools.partial、functools.wraps、functools.lru_cache?和?functools.reduce,感興趣的可以了解一下2024-03-03
Python發(fā)起請求提示UnicodeEncodeError錯誤代碼解決方法
這篇文章主要介紹了Python發(fā)起請求提示UnicodeEncodeError錯誤代碼解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
Python實現(xiàn)Excel數(shù)據(jù)同步到飛書文檔
這篇文章主要為大家詳細(xì)介紹了如何使用Python實現(xiàn)自動將Excel數(shù)據(jù)同步到飛書文檔的末尾,并添加時間戳,感興趣的小伙伴可以參考一下2025-02-02
如何使用Python JSON解析和轉(zhuǎn)換數(shù)據(jù)
JSON 是文本,使用 JavaScript 對象表示法編寫,Python 有一個內(nèi)置的 json 包,可用于處理 JSON 數(shù)據(jù),本文給大家介紹使用Python JSON解析和轉(zhuǎn)換數(shù)據(jù)的方法,感興趣的朋友跟隨小編一起看看吧2023-11-11

