流畅的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'
    >>> 




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