首页 > 代码库 > 第七节

第七节

类的方法

1.静态方法

class Dog(object):
def __init__(self,name):
self.name = name

@staticmethod
def eat(self):
print("%s is eating %s" % (self.name,"apple"))

def talk(self):
print("%s is talking"% self.name)

ainemo=Dog("tom")
ainemo.eat(ainemo)
ainemo.talk()
#只是名义上归类管理,实际上在静态方法里访问不了实例中的任何属性

显示结果:
tom is eating apple
tom is talking

2.类方法

class Dog(object):
name = "jack" #只有类变量才能在“类方法”中起作用
def __init__(self,name):
self.name = name #实例变量不起作用

@classmethod
def eat(self):
print("%s is eating %s" % (self.name,"apple"))

def talk(self):
print("%s is talking"% self.name)

d=Dog("tom")
d.eat()

#只能访问类变量,不能访问实例变量
显示结果:
jack is eating apple

3.属性方法

class Dog(object):
def __init__(self,name):
self.name = name
self.__food = None

@property #attribute
def eat(self):
print("%s is eating %s" % (self.name,self.__food))

@eat.setter
def eat(self,food):
print("food is %s" % food)
#print("修改成功,%s is eating %s" % (self.name,food))
self.__food = food

@eat.deleter
def eat(self):
del self.__food
print("删完了")

def talk(self):
print("%s is talking"% self.name)

d=Dog("tom")
d.eat
d.eat="banana"
d.eat
#del d.eat  #会报错,因为将self.__food整个变量删除了
#d.eat

#把一个方法变成一个静态属性
显示结果:
tom is eating None
food is banana
tom is eating banana

4.反射

   1.hasattr

 

class Dog(object):
def __init__(self,name):
self.name = name

def bulk(self):
print("%s is yelling....." % self.name)

def run(self):
print("%s is running....." % self.name)

d = Dog("tom")
choice = input(">>:").strip()
print(hasattr(d,choice))

 

显示结果:
>>:run
True

2.getattr
class Dog(object):
def __init__(self,name):
self.name = name

def bulk(self):
print("%s is yelling....." % self.name)

def run(self):
print("%s is running....." % self.name)

d = Dog("tom")
choice = input(">>:").strip()
# print(hasattr(d,choice))
#
print(getattr(d,choice))
getattr(d,choice)()

显示结果:
>>:run
<bound method Dog.run of <__main__.Dog object at 0x000000B2BFDC98D0>>
tom is running.....

3.setattr
def eat(self):
print("%s is eating....." %self.name)

class Dog(object):
def __init__(self,name):
self.name = name

def bulk(self):
print("%s is yelling....." % self.name)

def run(self):
print("%s is running....." % self.name)

d = Dog("tom")
choice = input(">>:").strip()
# print(hasattr(d,choice))
#
# print(getattr(d,choice))
# getattr(d,choice)()

if hasattr(d,choice):
# attr = getattr(d,choice)
setattr(d,choice,"jack")
print(getattr(d,choice))
else:
setattr(d,choice,eat)
print(getattr(d,choice))
d.eat(d)

显示结果:
>>:eat
<function eat at 0x000000C37E183E18>
tom is eating....






























第七节