### 動態(tài)添加屬性:
1. `對象.屬性名=xx`的形式铃岔。
2. 通過`setattr(對象,屬性名,這個屬性對應(yīng)的值)`來添加。
### 動態(tài)添加實例方法:
使用`types.MethodType`來添加俗冻。并且這個函數(shù)中要有self作為第一個參數(shù)。
### 動態(tài)添加類方法:
動態(tài)添加類方法比較簡單,直接將類對象添加一個屬性屋剑,指向一個函數(shù)就可以了。但是這個函數(shù)必須使用`@classmethod`來進行裝飾诗眨。并且這個函數(shù)的第一個參數(shù)必須是`cls`唉匾。
### 動態(tài)添加靜態(tài)方法:
動態(tài)添加靜態(tài)方法也比較簡單,直接將這個類對象添加一個屬性匠楚,并將這個屬性指向一個函數(shù)就可以了巍膘。但是這個函數(shù)必須使用`@staticmethod`來進行裝飾。并且這個函數(shù)不需要傳遞`self`和`cls`這些參數(shù)芋簿,因為她只是一個靜態(tài)方法而已峡懈。
### 刪除屬性:
1. `del 對象.屬性名`。
2. `delattr(對象,屬性名)`
### `__slots__`魔術(shù)變量:
用來限制一個類中与斤,只能添加指定的屬性肪康。
這個魔術(shù)變量只能在新式類中才能用,在舊式類中不能使用撩穿。
### 類也是對象:
在Python中磷支,一切皆為對象。包括類食寡。類是使用元類創(chuàng)建的雾狈。
### 動態(tài)的創(chuàng)建類:
使用`type`函數(shù)可以動態(tài)創(chuàng)建類:`type(類名,父類的元組,這個類的屬性以及對應(yīng)值的字典)`
### 什么是元類:
元類總而言之一句話,就是用來創(chuàng)建類對象的抵皱。
### 創(chuàng)建自己的元類:
在`Python2`中善榛,如果要指定這個類的元類,應(yīng)該修改`__metaclass__`魔術(shù)變量叨叙。
在`Python3`中锭弊,如果要指定這個類的元類,應(yīng)該在類定義的頭部擂错,指定`metaclass=xxx`
1. 使用函數(shù)的形式:
? ? ```python
? ? # 元類會自動將你通常傳給‘type’的參數(shù)作為自己的參數(shù)傳入
? ? def upper_attr(future_class_name, future_class_parents, future_class_attr):
? ? ? ? '''返回一個類對象味滞,將屬性都轉(zhuǎn)為大寫形式'''
? ? ? ? # 選擇所有不以'__'開頭的屬性
? ? ? ? attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
? ? ? ? # 將它們轉(zhuǎn)為大寫形式
? ? ? ? uppercase_attr = dict((name.upper(), value) for name, value in attrs)
? ? ? ? # 通過'type'來做類對象的創(chuàng)建
? ? ? ? return type(future_class_name, future_class_parents, uppercase_attr)
? ? ? ? class Foo(object):
? ? ? ? __metaclass__ = upper_attr
? ? ? ? bar = 'bip'
? ? ```
2. 使用類的形式:
? ? ```python
? ? class UpperAttrMetaclass(type):
? ? ? ? def __new__(cls, name, bases, dct):
? ? ? ? attrs = ((name, value) for name, value in dct.items() if not name.startswith('__'))
? ? ? ? uppercase_attr = dict((name.upper(), value) for name, value in attrs)
? ? ? ? return super(UpperAttrMetaclass, cls).__new__(cls, name, bases, uppercase_attr)
? ? ```