Python类的基本写法与注释风格介绍
作者:hitrjj 发布时间:2023-01-15 07:53:52
标签:Python,注释,风格
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


猜你喜欢
- 布尔表示两值之一:True 或 False。 布尔值在编程中,通常需要知道表达式是 True 还是 False。可以计算 Python 中的
- IronPython是一种在 .NET及 Mono上的 Python实现,由微软的 Jim Hugunin所发起,是一个开源的项目,基于微软
- 1.断点调试是啥?难不难?断点调试其实并不是多么复杂的一件事,简单的理解无外呼就是打开浏览器,打开sources找到js文件,在行号上点一下
- 目录需求描述步骤分析和前置知识代码实现写在最后需求描述手上现有若干份财务分析报告的Word文档,如下:每一份Word文档中的内容如下:为了方
- 今天实现一个进度条加载过程,dom结构其实就是两个div<div class="pbar"> <div
- 1.为何使用事务管理可以保证数据的完整性。事务(Transaction),就是将一组SQL语句放在同一批次内去执行,如果一个SQL语句出错,
- 很多网站注册时都会要求输入电子邮箱,其应用场景是比较广的,例如注册账号接收验证码、注册成功通知、登录通知、找回密码验证通知等。本文将介绍如何
- 本文实例讲述了Python实现的凯撒密码算法。分享给大家供大家参考,具体如下:一 介绍凯撒密码是一种非常古老的加密方法,相传当年凯撒大地行军
- 定义: 何为触发器?在SQL Server里面也就是对某一个表的一定的操作,触发某种条件,从而执行的一段程序。触发器是一个特殊的存储过程。
- 一、find_element_by_id()find_element_by_id()1.从上面定位到的元素属性中,可以看到有个id属性:id
- 为什么要用numpy Python中提供了list容器,可以当作数组使用。但列表中的元素可以是任何对象,
- 本文全部操作均在windows环境下安装 PythonPython是一种跨平台的计算机程序设计语言,它可以运行在Windows、Mac和各种
- 下面的代码中python2与python3的print使用区别,大家注意一下。python3需要加()才行。语法:for循环的语法格式如下:
- MySQL有多种方法导入多个.sql文件(里面是sql语句),常用的有两个命令:mysql和source。但是这两个命令的导入效率差别很大,
- 前言在Python的世界里,将一个对象以json格式进行序列化或反序列化一直是一个问题。Python标准库里面提供了json序列化的工具,我
- 存储函数也是过程式对象之一,与存储过程相似。他们都是由SQL和过程式语句组成的代码片段,并且可以从应用程序和SQL中调用。然而,他们也有一些
- 本文在上文的基础上重新实现支持多线程的服务器。以下为TCP客户端的程序代码:#!/usr/bin/env python3import sys
- 第一次写博客,实属心血来潮。为什么要写这篇博客呢?原因如下1、有一次我想配置数据库端口号时,找不到对应的解决方案2、是时候有个地方可以记录一
- SQL语句优化的原则:◆1、使用索引来更快地遍历表缺省情况下建立的索引是非群集索引,但有时它并不是最佳的。在非群集索引下,数据在物理上随机存
- Step 1:Creating a Linked Server. EXEC sp_addlinkedserver 'ADSI'