【Python基础】之函数、类和方法

一、函数

1. def定义函数

Python Shell:

def add(a,b):
    return a+b


>>>add(1,2)
3
def add(a=1,b=2):
    return a+b

>>>add()
3

>>>add(3,5)
8

2.类和方法
Python Shell:

class A(object):
    def add(self,a,b):
            return a+b

>>>count = A()
>>>print(count.add(1,2))
3

创建类时初始化:
Python Shell:

class A():
    def __init__(self,a,b):
                self.a = int(a)
                self.b = int(b)

    def add(m):
            return m.a + m.b

>>>count = A('1',2)
>>>print(count.add())
3

3.类的继承

class A():
    def add(self,a,b):
            return a+b


class B(A):
    def sub(self,a,b):
            return a-b

>>>print(B().add(1,2))
3
原文地址:https://www.cnblogs.com/Owen-ET/p/6978680.html