python之类的特殊方法

一、静态方法

静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,主要是一些逻辑属于类,但是和类本身没有交互,即在静态方法中,不会涉及到类中的方法和属性的操作。可以理解为将静态方法存在此类的名称空间中。事实上,在python引入静态方法之前,通常是在全局名称空间中创建函数。

静态方法只是在名义上归与类管理,实际上在静态方法里访问不了实例中的任何属性。

#Author:Anliu
class file():
    def __init__(self,name,inode):
        self.name = name
        self.inode = inode

    def open_file(self):  #(4)当传递一个参数,运行正常,充分证明,静态属性只是将类的方法
                          #与类隔离变成普通函数,方法内部参数调运不受影响。
        print("name:%s ;inode:%s file is opening..."%(self.name,self.inode))

    @staticmethod
    def delete_file(self,math):
        print("name:%s :inode:%s file is delete...%s"%(self.name,self.inode,math))

f1 =  file("f1","01001")
#(1)f1.delete_file()  #整正常访问
#f1.delete_file()
#(2)当加上静态方法后,在调运报错:
# TypeError: delete_file() missing 1 required positional argument: 'self'
#(3)此时delete_file()函数已经和类的实例变量没有任何关联重新调运
f1.delete_file(f1,"vim")

二、类方法

类方法是将类本身作为对象进行操作的方法。他和静态方法的区别在于:不管这个方式是从实例调用还是从类调用,它都用第一个参数把类传递过来

类方法只能访问类变量,不能访问实例变量。

#Author:Anliu
class ColorTest(object):
    color = "color"

    @classmethod
    def value(self):
        return self.color

class Red(ColorTest):
    color = "red"

class Green(ColorTest):
    color = "green"

g = Green()
print(g.value())
print(Green.value())

其中,基类做一个抽象共性,对于实际的颜色的值需要结合实际的类进行匹配。

三、属性方法

属性方法:将一个方法变成一个静态属性,对用户来讲是透明的,隐藏 了实现过程。

#Author:Anliu
class file():
    platform = "linux"
    def __init__(self,name,inode):
        self.name = name
        self.inode = inode
        self.__foo = None   #(2)初始化一个私有方法

    def open_file(self):
        print("name:%s ;inode:%s file is opening..."%(self.name,self.inode))

    @property
    #def delete_file(self,math):  #(2)直接传递参数将报错:TypeError: delete_file() missing 1 required positional argument: 'math'
    def delete_file(self):
        print("name:%s :inode:%s file is delete...%s  %s"%(self.name,self.inode,self.platform,self.__foo))

    @delete_file.setter          #(2)定义修改方法
    def delete_file(self,math):
        self.__foo = math        #(2)将参数传递给私有方法


f1 =  file("f1","01001")
#f1.delete_file()  #(1)添加属性方法后,本身就不是类的方法,并直接调运
                   #TypeError: 'NoneType' object is not callable

#f1.delete_file

#(2)如何通过属性方法传参?只能通过,重新定义修改方法
f1.delete_file = "vim"  #(2)传参
f1.delete_file

实例:

假如想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了,必须经历以下几步:

1. 连接航空公司API查询

2. 对查询结果进行解析

3. 返回结果给你的用户

因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,

#Author:Anliu

class Flight(object):
    def __init__(self,name):
        self.flight_name = name


    def checking_status(self):
        print("checking flight %s status " % self.flight_name)
        return  0

    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0 :
            print("flight got canceled...")
        elif status == 1 :
            print("flight is arrived...")
        elif status == 2:
            print("flight has departured already...")
        else:
            print("cannot confirm the flight status...,please check later")
    @flight_status.setter
    def flight_status(self,status):
        print("flight %s has changed status to %s" %(self.flight_name,status))
f = Flight("CA980")
f.flight_status
f.flight_status = 2

四、特殊成员方法

(1)__doc__  表示类的描述信息

#Author:Anliu
class test():
    '''
    The class implements the login function
    '''
    def __init__(self,name):
        self.name = name

    def login(self):
        print("login...")

fun1 = test("anliu")
print(fun1)   #打印类的实例对象
print(fun1.__doc__)  #打印类的描述信息:    The class implements the login function

(2) __module__ 和  __class__

  __module__ 表示当前操作的对象在那个模块

  __class__     表示当前操作的对象的类是什么

在bin下创建一个test5文件:

#Author:Anliu
class test():
    '''
    The class implements the login function
    '''
    def __init__(self,name):
        self.name = name

    def login(self):
        print("login...")

#fun1 = test("anliu")
#print(fun1)   #打印类的实例对象
#print(fun1.__doc__)  #打印类的描述信息:    The class implements the login function

在bin的同一级目录下创建文件object:

#Author:Anliu
from bin.test5 import test

obj = test("anliu")
print(obj.__class__)   #打印 <class 'bin.test5.test'>
print(obj.__module__)   #打印:bin.test5

(3) __init__ 构造方法,通过类创建对象时,自动触发执行。


(4)__del__析构方法,当对象在内存中被释放时,自动触发执行。


(5)__call__ 对象后面加括号,触发执行。

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

#Author:Anliu
class test():
    '''
    The class implements the login function
    '''
    def __init__(self,name):
        self.name = name

    def login(self):
        print("login...")

    def __call__(self, *args, **kwargs):  #定义__call__方法
        print(args,kwargs)

fun1 = test("anliu")
fun1("123","456","789",name="aoe")
#直接调运报错:TypeError: 'test' object is not callable
#定义__call__函数之后:('123', '456', '789') {'name': 'aoe'}


(6) __dict__ 查看类或对象中的所有成员 

#Author:Anliu
class test():
    '''
    The class implements the login function
    '''
    def __init__(self,name):
        self.name = name

    def login(self):
        print("login...")

    def __call__(self, *args, **kwargs):  #定义__call__方法
        print(args,kwargs)

print(test.__dict__)
#类中的成员:{'__module__': '__main__', '__doc__': '
    The class implements the login function
    ', '__init__': <function test.__init__ at 0x000001E650CFFD90>, 'login': <function test.login at 0x000001E650CFFE18>, '__call__': <function test.__call__ at 0x000001E650CFFEA0>, '__dict__': <attribute '__dict__' of 'test' objects>, '__weakref__': <attribute '__weakref__' of 'test' objects>}
fun1 = test("anliu")
print(fun1.__dict__)
#对象中的成员:{'name': 'anliu'}

(7)__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。


#Author:Anliu
class test():
    '''
    The class implements the login function
    '''
    def __init__(self,name):
        self.name = name

    def login(self):
        print("login...")

    def __call__(self, *args, **kwargs):  #定义__call__方法
        print(args,kwargs)

    def __str__(self):
        return "anliu"

fun1 = test("anliu")
#print(fun1)  #直接打印将返回对象的地址
print(fun1)#定义了__str__函数时,则返回:  anliu




(8)__getitem__、__setitem__、__delitem__

用于索引操作,如字典。以上分别表示获取、设置、删除数据

#Author:Anliu
class test():
    '''
    The class implements the login function
    '''
    def __init__(self,name):
        self.name = name

    def login(self):
        print("login...")

    def __call__(self, *args, **kwargs):  #定义__call__方法
        print(args,kwargs)

    def __str__(self):
        return "anliu"

    def __getitem__(self, item):
        print('__getitem__',item)

    def __setitem__(self, key, value):
        print('__setitem__',key,value)

    def __delitem__(self, key):
        print('__delitem__',key)

fun1 = test("anliu")
#result = fun1["k1"]   #__getitem__ k1
#fun1["k1"] = "v1"  #__setitem__ k1 v1
del fun1["k1"]
#fun1["k1"]
原文地址:https://www.cnblogs.com/anttech/p/12841662.html