classmethod与staticmethod isinstance与issubclass

classmethod

翻译:一个类方法

classmethod是一个装饰器,可以装饰给类内部的方法,使该方法绑定给类使用

​ 对象的绑定方法特殊之处

​ 由对象来调用,会将对象当作第一个参数传给该方法

​ 类的绑定方法特殊之处

​ 由类来调用,会将类当作第一个参数传给该方法

class People:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    @classmethod
    def tell_info(cls):#cls=People
        print(cls)
        print('此处是类方法')

p=People('tank',18)
p.tell_info()
'''
<class '__main__.People'>
此处是类方法'''
People.tell_info()
'''
<class '__main__.People'>
此处是类方法'''

staticmethod

staticmethod是一个装饰器,可以装饰给类内部的方法,使该方法既不绑定给对象,也不绑定给类

import hashlib
import uuid
import settings

class Teacher:
    def __init__(self,user,pwd):
        self.user=user
        self.pwd=pwd

    def index(self):
        if self.user=='tank' and self.pwd=='123':
            print('验证通过,显示主页')

    @classmethod
    def login_auth_from_settings(cls):
        obj=cls(settings.USER,settings.PWD)#个人认为就是调用了类
        return obj #Teacher()-->return obj

    @staticmethod
    def create_id():
        uuid_obj=uuid.uuid4()
        md5=hashlib.md5()
        md5.update(str(uuid_obj).encode('utf-8'))
        return md5.hexdigest()

obj=Teacher.login_auth_from_settings()
obj.index()#验证通过,显示主页

tea1=Teacher('tank','123')
tea1.index()#验证通过,显示主页

#import uuid #是一个加密模块,uuid4通过时间戳生成一个世界上唯一的字符串。
print(uuid.uuid4())#617e8e86-ea4b-4004-bc67-03984dd0d0e0
print(type(uuid.uuid4()))#<class 'uuid.UUID'>

print(Teacher.create_id())#9f9cb0402a68270ad629af2060656457
print(tea1.create_id())#f0973188d6964cb4f7259259b74b2c2c

isinstance

__class__:对象的属性,获取该对象当前类

isinstance(参数1,参数2):

​ python内置的函数,可以传入两个参数,用于判断参数1是不是参数2的一个实例。

​ 判断一个对象是否是一个类的实例。

issubclass

issubclass(参数1,参数2):

​ python内置的函数,可以传入两个参数,用于判断参数1是否是参数2的子类。

​ 判断一个类是否是另一个类的子类

class Foo:
    pass

class Goo(Foo):
    pass

foo_obj=Foo()
print(isinstance(foo_obj,Foo))#True
print(issubclass(Goo,Foo))#True

原文地址:https://www.cnblogs.com/zqfzqf/p/12591756.html