属性:
公有属性(属于类,每个类一份)
普通属性(属于对象,每个对象一份)
私有属性(属于对象,跟普通属性相似,只是不能通过对象直接访问)
class person():
# 公有属性
name=None
def __init__(self,age,score):
# 普通属性
self.age = age
# 私有属性
self.__socre = score
方法(按作用)
构造方法: init()通常在初始化一个类实例的时候调用
析构函数: del()当对象结束其生命周期的时候,系统会自动调用其析构函数,析构函数往往用于做一些“善后处理”工作,关闭程序所占用的资源
构造函数会为对象开辟一块内存空间,当对象执行完毕后,会调用析构函数进行释放所占用的内存给操作系统,析构函数没有参数也没有返回值
class Person(Object):
def __init__(self,name,age):
self.name = name
self.age = age
def __new__(cls,*args,**kwargs):
print("creat a new object")
return object.__new__(cls)
def __del__(self):
print("an object of deconsttuction")
方法(按类型)
普通方法:
私有方法(方法前面加两个下划线)
静态方法
类方法
属性方法
class Person():
def test0():
print("普通方法")
def __test1():
print("私有方法")
@staticmethod
def showTime():
print("静态方法")
@classmethod
def classMethod(cls):
print("类方法")
@property
def socore(self):
return self.__score
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError("score must be an integer!")
if value < 0 or value >100:
raise ValueError("score must between 0 ~ 100")
self.__score = value
静态方法
@staticmethod
静态方法,通过类直接调用,不需要创建对象,不会隐式传递self
类方法
@classmethod
类方法,方法中的self是类本身,调用方法时传的值也必须是类的共有属性
也就是说:类方法只能操作类本身的共有字段
init() 与 new()
同
二者均是python面向对象语言中的函数,new()比较少用,init()则用的比较多
异
__new__是在实例创建之前被调用的,因为他的任务就是创建实例然后返回给实例对象,是个静态方法。
__init__是当实例对象创建完成后被调用的,然后设置对象属性的一些初始值,通常用在初始化一个实例的时候,是一个实例方法
可以使用__new__来进行设计单例模式
class Singleton(object):
def __new__(cls):
if not hasattr(cls,'instance'):
cls.instance = super(Singleton,cls).__new__(cls)
return cls.instance