鍍金池/ 問答/Python/ 在def定義函數(shù)的時(shí)候, @和-> 代表什么?

在def定義函數(shù)的時(shí)候, @和-> 代表什么?

在閱讀別人的源碼的時(shí)候, 發(fā)現(xiàn)他大量的使用了這種方式定義函數(shù):

@property
def attrs(self) -> _Attrs:
    pass

不知道其中的@property-> _Attrs:是做什么用的? 請問哪里有相關(guān)的說明?

感謝.

回答
編輯回答
朕略萌

關(guān)于@property

這是一個(gè)python面向?qū)ο蟮木幊虇栴},比較簡單:

@property是一個(gè)裝飾器,它能夠使得類把一個(gè)方法變成屬性調(diào)用的。

比如,python類中,我想要訪問、設(shè)置私有變量,可以通過和C++類似的方式,如:

class Student(object):

    def get_score(self):
         return self._score

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value


s = Student()
s.set_score(60) # ok!
s.get_score()

不過,這樣看起來有些麻煩,實(shí)際上python獲取、設(shè)置類的變量(非私有變量)可以直接通過如下方式:

class Student(object):
    pass

s = Student()
s.score = 90
print(s.score) # 90

這樣看起來是不是很簡單?但是也有危險(xiǎn),這樣對于類的變量的賦值的類型是不可確定的,無法對變量賦值類型進(jìn)行檢查限制,比如可以賦值為整數(shù)、字符串、boolean變量等。想要實(shí)現(xiàn)這樣獲取值、賦值,也不是不行,通過@property就可以實(shí)現(xiàn):

class Student(object):
    @property
    def get_score(self):
         return self._score
    @property
    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

s = Student()
s.score = 90
print(s.score) # 90
s.score = '100' #報(bào)錯(cuò)

參考:廖雪峰的python教程--使用@property

關(guān)于 -> _Attrs

->常常出現(xiàn)在python函數(shù)定義的函數(shù)名后面,為函數(shù)添加元數(shù)據(jù),描述函數(shù)的返回類型,從而方便開發(fā)人員使用。比如:

def add(x, y) -> int:
  return x+y

這里面,元數(shù)據(jù)表明了函數(shù)的返回值為int類型。
至于樓主問題中的,-> _Attr則表明函數(shù)返回的是一個(gè)外部可訪問的類的私有變量。

參考:給函數(shù)參數(shù)增加元信息

2018年8月26日 02:40
編輯回答
兮顏

-> 第三方庫mypy, 要梯子:
http://mypy-lang.org

用于告訴python vm 涵數(shù)(x)的variable type和返回type, python 可以
dynamic and static typing 混合使用

以下是部份官方內(nèi)容:

Migrate existing code to static typing, a function at a time. You can freely mix static and dynamic typing within a program, within a module or within an expression. No need to give up dynamic typing — use static typing when it makes sense. Often just adding function signatures gives you statically typed code. Mypy can infer the types of other variables.

2018年4月16日 08:22
編輯回答
痞性

Google一下...

官方文檔函數(shù)定義這一節(jié)都有講

順便貼一下搜到的博文:
Python 函數(shù)注釋:奇怪的:,->符號
裝飾器

2017年4月18日 17:23