您的位置:首页 > 编程语言 > Python开发

Python类成员方法

2020-07-12 09:18 465 查看

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

#coding:utf-8
'''
1. 类;是一个模板,模板中包含了多个“函数”
2.对象;根据模板创建的实例(就是对象)。实例即是对象中的函数

类的成员:
类成员可以分为三大类:
1.实例属性(__init__()初始化实例里面的变量)
2.类属性(类里面的变量,初始化类的时候会一起加载到内存)
3.方法(类里面的函数)

'''
#类方法(@classmethod):
'''
说明
1.类方法不能通过实例调用
2.类方法只能通过类来调用
3.类方法不能访问实例变量
'''
class Animal(object):
hobbie = "meat"
def __init__(self,name):
self.name = name

@classmethod    #定义方法talk为类方法
def talk(self):
print("%s is talking..."%self.hobbie)

#实例调用类方法报错
#d = Animal("Eric")
#d.talk()    #AttributeError: type object 'Animal' has no attribute 'name'

#类调用类方法
Animal.talk()   #meat is talking...
#静态方法(@staticmethod):
'''
说明
1.当把方法变为静态方法后,这个方法跟实例就没关系了
2.在静态方法内,不能访问类变量和实例变量
'''
class Animal(object):
hobbie = "meat"
def __init__(self,name):
self.name = name

@staticmethod    #定义talk为静态方法
# def talk(self):
#     print("%s is talking...",self.name) #尝试访问实例变量,但是报错 #TypeError: talk() missing 1 required positional argument: 'self'
def talk():
print("is talking...") #is talking...   #不访问实例变量和类变量,则正常

#调用talk静态方法
d = Animal("Eric")
d.talk()
#把方法变成属性(@property ):
'''
说明
1.@property可以把方法转换成类属性
2.调用@property方法,也只能当做类属性来调用(不能加"()"调用)

作用:
@property方法;可以当做一个公共区域,给所有人调用
'''
class Animal(object):
hobbie = "meat"
def __init__(self,name):
self.name = name

@property   #定义habit方法为属性
def habit(self):
print("%s habit is haha..."%self.name)

@property
def total_players(self):
return 3

#调用habit方法报错(因habit方法以及被@property转换成属性了)
# d = Animal("Eric")
# d.habit()   #TypeError: 'NoneType' object is not callable

#把hobit当作属性调用
d = Animal("Eric")
d.habit     #Eric habit is haha...
print(d.total_players)

'''
问题:
1.用@property把方法转换为属性后,怎么传参呢?
可通过(@方法名.setter)这个装饰器,重写该方法后即可传参
'''
class Animal(object):
hobbie = "meat"
def __init__(self,name):
self.name = name
self.num = None

@property
def total_players(self):
return self.num

@total_players.setter   #通过.setter装饰器重写方法后,即可传值
def total_players(self,num):
self.num = num
print("total players:",self.num)

d = Animal("Eric")
#d.total_players(4)  #这样传参显然不行了
print(d.total_players)  #None
d.total_players = 4     #传值,num等于4
print(d.total_players)  #4
'''
问题:
1.如果要删除用@property定义的方法呢?
可通过(@方法名.deleter)删除转换的方法属性
'''
class Animal(object):
hobbie = "meat"
def __init__(self,name):
self.name = name
self.num = None

@property
def total_players(self):
return self.num

@total_players.setter
def total_players(self,num):
self.num = num
print("total players:",self.num)

@total_players.deleter  #删除total_players这个属性
def total_players(self):
print("total players go delted.")
del self.num    #删除属性里面的某项内容

d = Animal("Eric")
print(d.total_players)
d.total_players = 4
del d.total_players   #删除d.total_players
print(d.total_players)

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  def