python類基礎知識注意點

一、類的簡述

       類是面向對象編程的核心內容。通常把具有相同特徵(數據元素)與行爲(功能)的事物描述定義爲一個類,類是一個抽象的概念,把類實例化既可以得到一個對象。

因此,對象的抽象是類,類的具體化就是對象,也可以說類的實例是對象,類實際上就是一種數據類型。

類具有屬性,它是對象的狀態的抽象,用數據結構來描述類的屬性。類具有操作,它是對象的行爲的抽象,用操作名和實現該操作的方法來描述。

對象具有狀態,一個對象用數據值來描述它的狀態。對象還有操作,用於改變對象的狀態,對象及其操作就是對象的行爲。

比如:把人類即爲一個抽象的類,“老王”則爲一個的人即對象。每個對象都有一些相同的特徵,但具體的數值卻不一定相同。如:每個人都有“姓名”,“國籍”,“年齡”等特徵。還具有一些相同的行爲,如:“喫飯”,“睡覺”,“工作”等

可以簡潔的描述爲:Person ({"name", "country", "age"}, {"eat", "sleep", "work"})。

在這裏可以看到,類有兩種屬性:數據屬性,行爲屬性。在類中行爲屬性一般稱爲“方法”。

二、數據屬性

屬性有兩種,類屬性,實例屬性(對象的屬性),通常把所有對象共同擁有的屬性定義爲類屬性,如:每個人都只有兩隻眼等,實例屬性則時根據不同的對象賦值不一樣的值,如:姓名等

下面來看一個簡單的代碼實現:

class Person(object):

    eyes = 2         

 #這個表示類的全局變量,這個變量是類的屬性,不是實例的屬性,每個

#實例的值都相同,這個值,除非去改

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self, food):
        print("%s 喫:%s" % (self.name, food))

    def eye(self):
        print("%s" % (self.eyes))


p1 = Person("張三", 18)
p2 = Person("李四", 19)

print("類的屬性:", Person.__dict__)
print("對象p1的屬性:", p1.__dict__)
print("對象p2的屬性:", p2.__dict__)     #中間的逗號最後以一個空格輸出

p1.eat("番茄炒雞蛋")
p1.eye()


#輸出結果
類的屬性: {'__module__': '__main__', 'eyes': 2, '__init__': <function Person.__init__ at 0x000002059BABB6A8>, 'eat': <function Person.eat at 0x000002059BABB730>, 'eye': <function Person.eye at 0x000002059BABBAE8>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
對象p1的屬性: {'name': '張三', 'age': 18}
對象p2的屬性: {'name': '李四', 'age': 19}
張三 喫:番茄炒雞蛋
2

先輸出,類, p1, p2 的屬性,得出結論

1)實例化的對象只具備自己的數據屬性(不包括類屬性,即全局變量屬性比如 eyes)

(2)類的屬性包含:類的數據屬性(全局的那些)、函數屬性。

這裏要注意幾點:

1)方法的第一個參數不用傳值,但必須在定義,因爲Python解釋器,做了這樣的一件事,自動把調用的對象當作第一個參數傳值給方法,通常定義爲self(相當與c++ this)

2)對象訪問屬性的過程,查找屬性__dict__字典,找到就訪問這個屬性,當對象的屬性字典不存在該屬性時,則會去類屬性裏邊找,類裏邊也不存在時則會報錯

3)類屬性所有通過該類創建的對象都可以訪問

1、類屬性的增刪該查

class Person(object):
    # 類屬性添加的第一種方式
    eyes = 2

    def __init__(self, name):
        self.name = name

    def say(self, w):
        print("%s說了%s" % (self.name, w))


print("1--類的屬性:", Person.__dict__)

# 類屬性添加的第二種方式
Person.arm = 2
print("2--添加類的屬性:", Person.__dict__)

# 類屬性修改
Person.arm = 1
print("3--修改類的屬性:", Person.__dict__)

# 類屬性刪除
del Person.eyes
print("4--刪除類的屬性:", Person.__dict__

#輸出結果
1--類的屬性: {'__module__': '__main__', 'eyes': 2, '__init__': <function Person.__init__ at 0x000001A8F769B6A8>, 'say': <function Person.say at 0x000001A8F769B730>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
2--添加類的屬性: {'__module__': '__main__', 'eyes': 2, '__init__': <function Person.__init__ at 0x000001A8F769B6A8>, 'say': <function Person.say at 0x000001A8F769B730>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'arm': 2}
3--修改類的屬性: {'__module__': '__main__', 'eyes': 2, '__init__': <function Person.__init__ at 0x000001A8F769B6A8>, 'say': <function Person.say at 0x000001A8F769B730>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'arm': 1}
4--刪除類的屬性: {'__module__': '__main__', '__init__': <function Person.__init__ at 0x000001A8F769B6A8>, 'say': <function Person.say at 0x000001A8F769B730>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'arm': 1}

看代碼應該就差不多明白類屬性的操作了。

注:類屬性一般一經定義,不會在執行的過程中增加、刪除類的屬性

定義類屬性一般只用第一種方法,其它的騷操作了解就好,忘了它吧

2、實例屬性的增刪改查

class Person(object):

    def __init__(self, name):
        # 實例屬性添加第一種方式
        self.name = name

    def say(self, w):
        print("%s說了%s" % (self.name, w))


p1 = Person("張三")
p2 = Person("李四")
print("1--p1的屬性:", p1.__dict__)
print("1--p2的屬性:", p2.__dict__)

# 實例屬性添加第二種方式
p1.age = 20
print("2--p1的屬性:", p1.__dict__)
print("2--p2的屬性:", p2.__dict__)

# 刪除實例屬性
del p1.name
print("3--p1的屬性:", p1.__dict__)
print("3--p2的屬性:", p2.__dict__)

# 修改實例屬性
p1.age = 10
print("4--p1的屬性:", p1.__dict__)
print("4--p2的屬性:", p2.__dict__)


# 輸出結果
1--p1的屬性: {'name': '張三'}
1--p2的屬性: {'name': '李四'}
2--p1的屬性: {'name': '張三', 'age': 20}
2--p2的屬性: {'name': '李四'}
3--p1的屬性: {'age': 20}
3--p2的屬性: {'name': '李四'}
4--p1的屬性: {'age': 10}
4--p2的屬性: {'name': '李四'}

實例屬性跟類屬性的操作差不多。從上也可以得出結論,對對象 p1 的操作並不影響 p2 的屬性。

注:實例屬性一般放在init方法裏邊初始化,不會在執行的過程中增加、刪除對象的屬性

三、方法

1、普通的方法

上邊沒有@符號修飾,供外部實例調用,普通的方法也叫實例方法,但雖然叫實例方法但卻與類相關,存儲在類的屬性中

2、類方法

上邊有@classmethod修飾,定義時第一個參數必須爲"cls",並通過cls來調用類屬性,無法訪問實例屬性

3、靜態方法()

上邊有@staticmethod,與類相關但不需要訪問屬性,無法調用其它方法與屬性

class Person(object):
    eyes = 2

    def __init__(self, name):
        self.name = name

    def say(self, w):  # 普通方法
        print("%s say %s" % (self.name, w))

    @classmethod
    def cls_md(cls):  # 類方法
        print("這是類方法", cls.eyes)

    @staticmethod
    def stat():  # 靜態方法
        print("這是靜態方法")


p1 = Person("zhangs")
print(Person.__dict__)
p1.say("hello")
p1.cls_md()
p1.stat()

# 輸出結果
{'__module__': '__main__', 'eyes': 2, '__init__': <function Person.__init__ at 0x000001DF5205B6A8>, 'say': <function Person.say at 0x000001DF5205B730>, 'cls_md': <classmethod object at 0x000001DF5205ABE0>, 'stat': <staticmethod object at 0x000001DF5205AEB8>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
zhangs say hello
這是類方法 2
這是靜態方法

4、方法的增(瞭解即可)

class Person(object):
    eyes = 2

    def __init__(self, name):
        self.name = name


def say2(self):  # 普通方法
    print("%s 增加普通方法" % (self.name))


@classmethod
def ha2(cls):  # 類方法
    print("增加類方法", cls.eyes)


@staticmethod
def stat2():  # 靜態方法
    print("增加靜態方法")


print("增加前:", Person.__dict__)
Person.say2 = say2
Person.ha2 = ha2
Person.stat2 = stat2
print("增加後:", Person.__dict__)
p1 = Person("zhangs")
p1.say2()
p1.ha2()
p1.stat2()


# 輸出結果
增加前: {'__module__': '__main__', 'eyes': 2, '__init__': <function Person.__init__ at 0x000001468207B6A8>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
增加後: {'__module__': '__main__', 'eyes': 2, '__init__': <function Person.__init__ at 0x000001468207B6A8>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'say2': <function say2 at 0x0000014681ECC1E0>, 'ha2': <classmethod object at 0x000001468207A390>, 'stat2': <staticmethod object at 0x000001468207AB70>}
zhangs 增加普通方法
增加類方法 2
增加靜態方法

四、私有化

1、xx:公有變量

2、_xx:單前置下劃線,私有化屬性或方法,類對象和子類可以訪問,from module import * 禁止導入,但from module import _xx  或 Import module還可以導入

3、__xx:雙前置下劃線,私有屬性或方法,外部無法訪問到(因爲名字重整了,__xx變爲_classname__xx),兼具_xx的特性

4、__xx__:前後雙下劃線,用戶名空間的魔法對象或屬性,例如:__init__,一般不��自己定義這樣的變量名

5、xx_:單後置下劃線,與python關鍵字重名+_區分,不要定義這樣的變量名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章