網站首頁 編程語言 正文
Python類基本寫法與注釋風格
python是一種面向對象的語言,利用類的抽象可以大大提高代碼的復用和結構,減少重復造輪子的過程,也讓代碼變得更加清晰易懂、便于維護。
1.python中的類 Class
python中的類提供了一系列數據和方法的組合,類是python的一種對象,可以由它構建出新的實例。實例包含了類所具有的屬性和類中聲明的方法。首先來看一個基本類的寫法:
class Dog(object):
"""This is a dog class as example"""
def __init__(self,name):
"""This is initial funciton"""
self.name = name
def voice(self):
"""Dog will speak as wangwang """
print('WangWangWang')
這是一個非常簡單的類,但其中包含了類很重要的幾個部分,包括類的聲明、初始化的構造函數、屬性、成員方法的定義等。
其中有幾個地方需要注意:object是python中所有類的基類,在類的初始化時顯式繼承?
self是類里的實例,為實例本身,在初始化后具有一系列的屬性和方法,類方法的第一個參數按照約定需要使用self開頭。
一個完整的類的聲明還會包括基本屬性、私有屬性和保護變量等內容:
class Dog(object):
"""This is a dog class as example"""
animal_kind = 'dog' #基本屬性
animal_legs = 4 #基本屬性也建議寫到初始化構造函數中去
def __init__(self,name,age,params...): #利用__init__(self,params)進行初始化
"""This is initial funciton"""
self.name = name
self.age = age
#還可以定義各種其他的屬性,作為實例初始化時候將傳進來的參數進行賦值
self.__gender = 'male' #兩個下劃線開頭是私有內部屬性,只能在類內訪問
def __privateGender(self):
"""This is pravate method"""
print('This dog gender is %s',self.__gender)
def voice(self):
"""Dog will speak as wangwang """
print('WangWangWang')
print(self.__privateGender(self))
def run(self):
"""runing with legs"""
print("This dog has %d legs to run"%self.animal_legs)
#定義一大堆各種各樣的方法
class是可以進行繼承以及方法重寫的,可以基于一個類繼承,也可以基于多個類進行多重繼承。
class Husky(Dog):
"""Husky inherent the Dog attris and method"""
def __init__(self,name,age,color,params):
Dog.__init__(self, name, age) #利用Dog這個父類的初始化
self.color = color #子類中特定屬性的初始化
def jump(self):
"""Husky special jump function"""
print('This dog could jump jump')
def voice(self):
"""重寫覆蓋父類的函數,實現自己的特殊的方法"
print('AoAoAoWu~~~~~~')
2.語言風格規范
為了更好的便于閱讀和復用代碼,還需要使得代碼滿足一定的語言風格,這里選用了google的風格規范來對類進行聲明,下面是一個例子
# ref from:https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/
class MyDog(object):
"""Summary of class here. #1.首先一句話簡短的總結這個類的功能和作,文檔字符串需要用三引號包括
# 對齊,空一行
If the class has public attributes, they may be documented here
in an ``Attributes`` section and follow the same formatting as a
function's ``Args`` section. Alternatively, attributes may be documented
inline with the attribute's declaration (see __init__ method below).
Properties created with the ``@property`` decorator should be documented
in the property's getter method.
Longer class information.... #隨后詳細的說明類的細節
Longer class information.... #類內部第一行的開始的文字都可以被__doc__
# 空一行,開始寫這個類的各個屬性,包括數據類型和作用
Attributes:
likes_spam: A boolean indicating if we like SPAM or not. #屬性的聲明,包括數據類型和作用,xxx類型的數據for/used to/ofxxx
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
# 下面是詳細的例子
"""Example of docstring on the __init__ method.
# 對于初始化方法的說明
The __init__ method may be documented in either the class level
docstring, or as a docstring on the __init__ method itself.
Either form is acceptable, but the two should not be mixed. Choose one
convention to document the __init__ method and be consistent with it.
# 對于初始化方法的一些記錄
Note:
Do not include the `self` parameter in the ``Args`` section.
# 初始化的參數輸入,對于方法來說參數名(數據類型):描述的格式來寫
Args:
param1 (str): Description of `param1`.
param2 (:obj:`int`, optional): Description of `param2`. Multiple
lines are supported.
param3 (:obj:`list` of :obj:`str`): Description of `param3`.
"""
self.likes_spam = likes_spam
self.eggs = 0
# 輸入參數的初始化
self.attr1 = param1
self.attr2 = param2
self.attr3 = param3 #: Doc comment *inline* with attribute
#: list of str: Doc comment *before* attribute, with type specified
self.attr4 = ['attr4']
self.attr5 = None
"""str: Docstring *after* attribute, with type specified."""
def public_method(self):
"""Performs operation blah."""
"""Summary line. #第一行簡寫函數描述
# 空一行,對齊詳細描述
Extended description of function.
# 空一行對齊,寫args 的各個內容,變量名(類型):描述
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
# 空一行對齊,不同情況下的if else 返回值(類型):描述
Returns:
int/float/bool dtype: Description of return value
"""
Example
最后完整的按照風格來寫一個類的示例:
class Dog(object):
"""
This is a class for Dog
Dog class is the parents class of all dog, this class contain
general attributes of dog and some common function of dogs, such as
num legs, the voice fucntion, the runing functions.
Attributes:
name: A string of dog's name
kind: A string of dog's family
age: A integer of dog years
gender: A boolean gender of dog, male=1 of famle=0
legs A integer if dog's legs
weight: A float of dogs weight
size: A string of dogs, one of big, middle, smal
"""
def __init__(self,args,gender,size):
"""initialize dog class, all attributes pass in with args, which is a dict or indepent params
Input contain dict and str params, also there is private attribute
Args:
args.name(str): dog name
args.kind(str): dog family
args.age(int) : dog age
gender(bool) : dog gender, male=1,famale=0
args.weight(float): dog weight
size(str) : dog size
"""
self.name = args.name
self.kind = args.kind
self.age = args.age
self.weight = args.weight
# __legs(int) : dog legs,privite attribute, not the inputs params,寫在前面用#做注釋,不屬于輸入的參數的初始化
self.__legs = 4
"""寫在后面用三引號__legs(int) : dog legs,privite attribute"""
self.size = size
self.gender = gender
def voice(self,size):
"""This is dog speak fucntion
Different dog with different voice
which related to the size,age and kind
Args:
size(str): dog size
age(int) : dog age
kind(srt): dog kind
Returns:
None, just print the voice
"""
if size=='big':
print('Big WangWang')
elif size =='middle':
print('M wang')
elif size=='small':
print('Miao')
# 附注:return 可從任意深度跳出函數,None
Python類的簡單寫法
class MyClass:
name = ''
age = 0
__weight = 0 #私有變量
def __init__(self, n, a, w): #self必須作為函數的第一個參數
self.name = n
self.age = a
self.__weight = w
def speak(self):
print('%s 說:我 %s 歲'%(self.name, self.age))
x = MyClass('yao', 10, 30)
x.speak()
原文鏈接:https://blog.csdn.net/u014636245/article/details/98856454
相關推薦
- 2023-03-19 教你如何實現在react項目中嵌入Blazor_React
- 2022-06-06 Anaconda安裝pytorch和paddle的方法步驟_python
- 2022-06-21 Android?studio實現兩個界面間的切換_Android
- 2023-01-23 C#實現鼠標左右鍵切換效果_C#教程
- 2022-06-20 Python隨機驗證碼生成和join?字符串的問題解析_python
- 2022-10-23 python如何在一個py文件中獲取另一個py文件中的值(一個或多個)_python
- 2022-05-20 springCloud_Feign遠程調用
- 2024-01-30 關閉scrapy的UserWarning: Selector got both text and r
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支