Python3 中類的反射

2022-07-29 09:33:13 字數 1036 閱讀 8156

1.針對類中方法的反射

#  反射的使用

class dog(object):

def __init__(self,name):

self.name = name

def eat(self):

print('%s is eating...'%self.name)

def bulk(self):

print('%s is yaling...'%self.name)

d = dog('wt')

choice = input('>>:').strip()

if hasattr(d,choice):

func = getattr(d,choice)

func()

else:

setattr(d,choice,bulk)

func = getattr(d, choice)

func(d)

2.針對類成員變數的使用

#  反射的使用

class dog(object):

def __init__(self,name):

self.name = name

def eat(self):

print('%s is eating...'%self.name)

def bulk(self):

print('%s is yaling...'%self.name)

d = dog('wt')

choice = input('>>:').strip()

if hasattr(d,choice):

print(getattr(d,choice))

else:

setattr(d,choice,'hjc')

print(getattr(d,choice))

總的來說就是判斷是否有輸入的choice,若有則進行輸出,若沒有則進行賦值或者替換。

python3元類 python3元類的呼叫順序

在嘗試理解元類建立類例項的順序時,我感到困惑.根據該圖 source 我鍵入以下 進行驗證.class meta type def call self print meta call super meta,self call def new mcs,name,bases,attrs,kwargs p...

python3中的類和物件

什麼是物件 從同乙個類中具體化描述的乙個事物被稱之為物件 什麼是類 具有相同特性和方法的抽象概念稱之為類 類和物件之間的關係 類是物件的抽象概念,物件是類的詳細例項化 python3中如何定義類以及類中的屬性方法 語法部分 1.如何定義乙個類 classpeople 定義乙個people類 2.如何...

Python3中的類和例項

1.類和例項class 類名 父類 基類 超類列表 passclass student def init self,name,age self.name name self.age age def printinfo self print name format self.name age form...