第七节

Posted 酷酷的狐狸

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第七节相关的知识,希望对你有一定的参考价值。

类的方法

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....






























以上是关于第七节的主要内容,如果未能解决你的问题,请参考以下文章

《Nuitka打包实战指南》第七节 启用插件

Linux内核第七节 20135332武西垚

第七节 继承抽象类和接口

第七节:CNN练习2手势识别

《树莓派项目实战》第七节 使用声音传感器检测有无声音

jquery第七节