流暢的python 筆記 第 9 章:符合Python風格的對象

1. 對象表示

    repr,str可以返回對象的字符串形式



2. classmethod與staticmethod


    classmethod 修飾符對應的函數不需要實例化,不需要 self 參數,但第一個參數需要是表示自身類的 cls 參數,可以來調用類的屬性,類的方法,實例化對象等。

  >>> class A:
        def func1(self):
            print('foo')
        @classmethod
        def func2(cls):
            print('func2')
            cls().func1()

            
    >>> A.func2()
    func2
    foo
    >>> 


staticmethod不強制要求傳遞參數,如下聲明一個靜態方法:

    class C(object):
        @staticmethod
        def f():
        print('xxxxxx');
    
    C.f();          # 靜態方法無需實例化
    cobj = C()
    cobj.f()        # 也可以實例化後調用



3. property屬性

property用於返回類中的屬性值。

       >>> class Pfoo(object):
        def __init__(self):
            self._tage = 100
        @property
        def tage(self):
            return self._tage

        
    >>> foo = Pfoo()
    >>> foo.tage
    100
    >>> 

    property 的 getter,setter

        >>> class Pfoo(object):
            def __init__(self):
                self._tage = 100
            @property
            def tage(self):
                return self._tage
            @tage.setter
            def tage(self,value):
                self._tage = value

                
        >>> foo = Pfoo()
        >>> foo.tage=1024
        >>> foo.tage
        1024


4. public 、private成員變量、成員函數


    python默認的成員變量、成員函數都是public的

    聲明爲prvate的方法爲在變量、函數名的命名前加 "__"(2個下劃線),如果是多餘2個的下劃線一樣被視爲private的

   
    >>> class Aobj(object):
        def __init__(self):
            self.name = 'zval'
        def __func(self):
            print(self.name)

            
    >>> a = Aobj()
    >>> a
    <__main__.Aobj object at 0x011899F0>
    >>> dir(a)
    ['_Aobj__func', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
    >>> a.__func()
    Traceback (most recent call last):
      File "<pyshell#41>", line 1, in <module>
        a.__func()
    AttributeError: 'Aobj' object has no attribute '__func'
    >>> 




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