- 在类中,我们在定义每一个函数的时候都需要加上一个self,其作用就相当于门牌号的作用,用于标识哪一个实例化的对象在调用方法。同样,在函数的中定义一个变量时,如果我们希望该变量能够被该类中其他函数或者实例所调用,那么我们需要在定义变量的时候在其前加上self.
例如:
class Tickle:
def __init__(self,childern,adult,date):
self.childern = childern
self.adult = adult
self.date = date
def TicklePrice(self):
if self.adult > 0:
self.price = self.adult * 100
if self.childern > 0:
self.price += self.childern*50
if self.date == '周日' :
self.price = self.price*1.2
return self.price
def PrintPrice(self):
print('您的票价总共要花费%d'%self.price)
在定义了__init__函数和TicklePrice函数中变量如上所示
- 如果我们没有使用self. 来表示变量,则在该函数外的其他函数或者实例对象想要访问该变量则会报错
例如:
class Tickle:
def __init__(self,childern,adult,date):
self.childern = childern
self.adult = adult
self.date = date
def TicklePrice(self):
if self.adult > 0:
price = self.adult * 100
if self.childern > 0:
price += self.childern*50
if self.date == '周日' :
price = self.price*1.2
return price
def PrintPrice(self):
print('您的票价总共要花费%d'%self.price)
在试图用实例化的对象访问price属性或在PrintPrice函数中访问price是会报属性错误
AttributeError: 'Tickle' object has no attribute 'price'
上文的意思是说我们并没有在Tickle类下定义price属性,也就是说实例对象只能访问类下定义的属性,如果在函数体内定义的未用self标识,则实例对象不可访问。
class test:
n =100
def x(self):
k = 1000
m = test
调用:
m.n
Out[29]: 100
m.k
Traceback (most recent call last):
File "<ipython-input-30-19067ae45173>", line 1, in <module>
m.k
AttributeError: type object 'test' has no attribute 'k'
- python规定类中函数的调用和属性访问必须要有对实例对象
class test:
n = 100
def x(self):
n = n + 5
m = test()
函数x()中,试图访问n变量,会报错,因为在类中,访问属性要有实例对象或类对象。
error:
UnboundLocalError: local variable 'n' referenced before assignment
正确的写法为:
class test:
n = 100
def x(self):
self.n = self.n + 5
m = test()
或者写为:
class test:
n = 100
def x(self):
test.n = test.n + 5
m = test()