1、创建对象
''' 在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同, 类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。 ''' #!/usr/bin/python3 #类定义 class People: #定义基本属性 name = '' age = 0 #定义私有属性,私有属性在类外部无法直接进行访问 __weight = 0 #定义构造方法 def __init__(self,name,age,weight): self.name = name self.age = age self.__weight = weight #定义普通方法 def speak(self): print("name=%s, age=%d" %(self.name, self.age)) def __str__(self): return "name=%s, age=%d" %(self.name, self.age) # 实例化类 p = People('tom', 10, 30) p.speak() print("name=%s, age=%d" %(p.name, p.age)) print("*" * 10) print(p)
2、__del__方法
import sys class MyClass: def __del__(self): print("执行__del__方法。。。") # 实例化类 x1 = MyClass() x2 = x1 # 查询对象的引用个数 print("引用个数:", sys.getrefcount(x1)) print("引用个数:", sys.getrefcount(x2)) del x1 print("*" * 20) del x2 #对象的引用计数为0时调用__del__方法 print("*" * 20)
3、类属性和实例属性
#类定义 class People: #定义基本属性 name = '' age = 0 #定义私有属性,私有属性在类外部无法直接进行访问 __weight = 0 #定义构造方法 def __init__(self,name,age,weight): self.name = name self.age = age self.__weight = weight #定义普通方法 def speak(self): print("name=%s, age=%d" %(self.name, self.age)) def __str__(self): return "name=%s, age=%d" %(self.name, self.age) # 实例化类, 并访问实例属性的值 p = People('tom', 10, 30) p.speak() print("name=%s, age=%d" %(p.name, p.age)) print("*" * 10) print(p) # 访问类属性的值 print("name=%s, age=%d" %(People.name, People.age))
4、类方法、实例方法、静态方法
class People: #定义基本属性 name = '' def __init__(self, name): self.name = name #实例方法 def printName(self): print(self.name) #类方法 @classmethod def setName(cls, name): cls.name = name #静态方法 @staticmethod def sayHi(): print("hello world") People.setName("tom") print(People.name) People.sayHi() print("*" * 20) # 类方法与静态方法也可以通过对象类调用 p = People("jack") p.printName() p.setName("haha") print(People.name) p.sayHi()
5、__new__方法
class People(object): name = "" def __init__(self, name): self.name = name print("init...") def __del__(self): print("del...") def __new__(cls, name): print("new...") return object.__new__(cls) p = People("tom") print(p.name)
6、单例
class People(object): __instance = None def __new__(cls): if cls.__instance == None: cls.__instance = object.__new__(cls) return cls.__instance p1 = People() print(id(p1)) p2 = People() print(id(p2))
__init__方法调用了多次
class People(object): __instance = None def __new__(cls, name): if cls.__instance == None: cls.__instance = object.__new__(cls) return cls.__instance def __init__(self, name): self.name = name p1 = People("tom") print(id(p1)) print(p1.name) #tom p2 = People("jack") print(id(p2)) print(p2.name) #jack
只初始化一次
class People(object): __instance = None __flag = False def __new__(cls, name): if cls.__instance == None: cls.__instance = object.__new__(cls) return cls.__instance def __init__(self, name): if People.__flag == False: self.name = name People.__flag = True p1 = People("tom") print(id(p1)) print(p1.name) p2 = People("jack") print(id(p2)) print(p2.name)