1. 程式人生 > >第七節

第七節

setattr static 靜態屬性 set 類方法 訪問 att pan 變量

類的方法

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






























第七節