Python學習筆記(十)
一、類和構造函數的定義
class 類名(object):
def __init__(self,name,score):
self.name = name
self.score = score
def show_info(self):
print("name=",name,"score=",score)
類名通常大寫
二、通過變量生成實例
student1 = Student("cq",100)
三、自由的為對象實例添加屬性
student1 = Student("cq",100)
student1.school = "school"
四、訪問權限限制
name : public的,外界可訪問
__name__ :特殊的,外界可以訪問
__name:私有的
_name:私有的,外界可訪問,但請將其視為私有的
五、獲取對象信息
type(對象)
type(123)==int
import types
type(fn) = types.FunctionType #判斷是否為函數類型
type(fn) == types.BuiltinFunctionType
type(fn) == types.LambdaType
type(fn) == types.GeneratorType
isinstance(對象,類型)
dir(對象)
六、__XX__特殊方法
類似__XX__的是特殊方法,在Python中有特殊用途,例如使用len()函數時將自動調用對象中的__len__
七、動態增加實例屬性
對象.屬性 = 屬性值
八、類屬性
類屬性是屬於類的,可以在類中直接定義,但其實例也可以訪問類屬性
class Person:
name = "CQ"
def __init__(self):
pass
九、動態綁定方法
def show_info(self):
print("Hello World!")
from types import MethodTypes
s.show_info = MethodTypes(show_info(),s)
s.show_info()
十、動態綁定類方法
from types import MethodTypes
calss S(object):
pass
def show(self):
print("Hello")
s1 = S()
s1.show()
十一、限制動態添加的實例屬性
Python語言支持限制可以動態添加的實例屬性,通過__slots__可指定動態添加的屬性
class S(object):
__solts__ = ("name","age")
十二、為類設置屬性
通過使用Python內置的裝飾器@property可以將方法中的變量設置為屬性,@property設置於getter方法
class Student(object):
def __init__(self,name,age):
self.__name = name
self.__age = age
@property
def name(self):
return self.__name
@name.setter
def name(self,value):
self.__name = value
@proprety
def age(self):
return self.__age
本實例中將 get_name 和 set_name 合並封裝為了類的屬性name,並將age封裝設置為了類的只讀屬性
Python學習筆記(十)