多態(tài)
python是一種運(yùn)行時(shí)語言,python即支持面向過程彼宠,也支持面向?qū)ο?/p>
class Dog(object):
def print_self(self):
print("汪汪汪汪汪汪")
class xiaotq(Dog):
def print_self(self):
print("hahahhahaahha")
def introduce(temp):
temp.print_self()
dog1 = Dog()
dog2 = xiaotq()
introduce(dog1)
introduce(dog2)
類屬性和實(shí)例屬性
實(shí)例屬性:和具體的某個(gè)實(shí)例對象有關(guān)系,并且一個(gè)實(shí)例對象和另一個(gè)實(shí)例對象不共享屬性
類屬性類屬性所屬于類對象,并且多個(gè)實(shí)例對象之間共享一個(gè)類屬性
class Tool(object):
#屬性
num = 0
#方法
def __init__(self,new_name):
self.name = new_name
Tool.num += 1
tool1 = Tool("錘子")
tool2 = Tool("鐵鍬")
tool3 = Tool("水桶")
print(Tool.num)
結(jié)果:3
類方法辜梳、實(shí)例方法、靜態(tài)方法
類方法和實(shí)例方法必須傳參數(shù)泳叠,靜態(tài)方法可以沒有
class Game(object):
#屬性
num = 0
#實(shí)例方法
def __init__(self):
self.name = "王者榮耀"
Game.num += 1
#類方法
@classmethod
def add_num(cls):
cls.num = 100
#靜態(tài)方法
@staticmethod
def print_menu():
print("----------------")
print("王者榮耀")
print("_________________")
game = Game()
#類方法可以用類的名字調(diào)用方法作瞄,還可以通過類創(chuàng)建出來的對象去調(diào)用這個(gè)類方法
game.add_num()
print(Game.num)
Game.print_menu()
game.print_menu()
new方法
new方法是創(chuàng)建,init方法是初始化這兩個(gè)方法相當(dāng)于c++里的構(gòu)造方法危纫。
class Dog(object):
def __init__(self):
print("init***********")
def __del__(self):
print("del__________")
def __str__(self):
print("str&&&&&&&&&&&&&")
def __new__(cls):
print("new+++++++++++")
return object.__new__(cls) #如果沒有這一句就只能打印new
xtq = Dog()
運(yùn)行結(jié)果:
new+++++++++++
init***********
del__________
單例模式
class Dog(object):
pass
a = Dog()
print(id(a))
b = Dog()
print(id(b))
運(yùn)行結(jié)果:
4303201280
4331156144
class Dog(object):
__instance = None
def __new__(cls):
if cls.__instance == None:
cls.__instance = object.__new__(cls)
return cls.__instance
else:
return cls.__instance
a = Dog()
print(id(a))
b = Dog()
print(id(b))
運(yùn)行結(jié)果:
4331156200
4331156200
class Dog(object):
__instance = None
def __new__(cls,name):
if cls.__instance == None:
cls.__instance = object.__new__(cls)
return cls.__instance
else:
return cls.__instance
def __init__(self,name):
if Dog.__init_flag == False:
self.name = name
Dog.__init_flag == True
a = Dog("旺財(cái)")
print(a.name)
print(id(a))
b = Dog("嘯天犬")
print(id(b))
print(b.name)
運(yùn)行結(jié)果:
旺財(cái)
4331156256
4331156256
嘯天犬