多态
python是一种运行时语言,python即支持面向过程,也支持面向对象
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)
类属性和实例属性
实例属性:和具体的某个实例对象有关系,并且一个实例对象和另一个实例对象不共享属性
类属性类属性所属于类对象,并且多个实例对象之间共享一个类属性
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)
结果:3
类方法、实例方法、静态方法
类方法和实例方法必须传参数,静态方法可以没有
class Game(object):
#属性
num = 0
#实例方法
def __init__(self):
self.name = "王者荣耀"
Game.num += 1
#类方法
@classmethod
def add_num(cls):
cls.num = 100
#静态方法
@staticmethod
def print_menu():
print("----------------")
print("王者荣耀")
print("_________________")
game = Game()
#类方法可以用类的名字调用方法,还可以通过类创建出来的对象去调用这个类方法
game.add_num()
print(Game.num)
Game.print_menu()
game.print_menu()
new方法
new方法是创建,init方法是初始化这两个方法相当于c++里的构造方法。
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()
运行结果:
new+++++++++++
init***********
del__________
单例模式
class Dog(object):
pass
a = Dog()
print(id(a))
b = Dog()
print(id(b))
运行结果:
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))
运行结果:
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("旺财")
print(a.name)
print(id(a))
b = Dog("啸天犬")
print(id(b))
print(b.name)
运行结果:
旺财
4331156256
4331156256
啸天犬