Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
(1) functions defined in the class, called: Method
(2) defined outside the class of functions, called: global functions
Note point method:
The first parameter (1) The method must be: self, and can not be omitted
(2) However, "method" when calling, without providing the self parameter
(3) before the method call must instantiate "class "example of embodiment: the class name
plus" () ", for example: My ()
(. 4) one unit of whole indentation, which indicates the contents belong to the class of body weight
E.g:
class ex: #class定义一个类,类名:example
def walk(self): #定义一个walk方法,让类具有”散步“的能力
print("散步:take a walk")
def say(self,x): #定义一个say方法,让类具有”说话“的能力
print(x)
ai = ex() #实例化类(因为调用类中的方法,必须先实例化)
ai.walk() #执行散步指令,self不用提供
y = "可以说话:i kan speak"
ai.say(y) #执行说话指令,self在调用时,不用提供
Question 2: Argument Examples class
class exm:
def __init__(self,x,y=0): #初始化函数,使用内嵌函数:__init__(),进行初始化,具有两个初始化变量:x、y
self.x = x
self.y = y
def sum(self): #定义初始化数据的"方法(函数)"
return self.x + self.y
a = exm(3) #传参数3,进行参数实例化
print("当执行参数3的类,方法结果是:",a.sum())
print('\n')
b = exm(3,7) #传参数3,7,进行参数实例化
print("当执行参数3,4的类,方法结果是:",b.sum())