python进阶_类

常用内建属性

# 函数
__new__ #创建实例所需的方法
__init__ #构造初始化函数,在__new__内部调用

__repr__ #值打印时调用,打印返回值
__call__ #实例当函数调用时执行
__iter__ #返回迭代器,实例被迭代执行时先调用此函数

__getitem__ #下标读取不在属性时调用
__setitem__ #下标设置属性时调用,self.__dict__[k]=v
__delitem__ #下标删除实例属性时调用

__getattr__ #.操作读取时调用
__getattribute__ #.操作读取时调用,定以后个体attr不生效
__setattr__ #.操作设置属性时调用
__delattr__ #.操作删除实例属性时调用

# 格式转换
__int__ #被int包裹时调用,返回转换结果
__str__ #被str包裹时调用,返回转换结果

# 运算符重载
__add__ #加法,返回运算结果,__add__(self,other)

# 实例属性
__class__ #返回实例所在的类
__dict__ #实例的自定义属性
__doc__ #类文档,help(类或者实例)

# 类属性
__bases__ #当前类的所有父类

类相关内置函数

isinstance(object,classinfo) #判断实例是否属于类
issubclass(class,classinfo) #判断继承关系
hasattr(object,name) #判断存在
getattr(object,name) #获取
setattr(object,name,value) #修改或设置属性
delattr(object,name) #删除实例属性
dir([object]) #返回参数的属性、方法列表,无参数获取当前模块
super(type[, object-or-type]) #获取type的父类

类属性和实例实行

__dict__:只返回实例属性
dir([object]):返回所有属性

__new__

  • 真正的构造函数
class C:
	def __new__(cls, *args, **kwargs):
		print('new')
	    new=super(cls,cls).__new__(cls, *args, **kwargs)
		# 返回new时会自动调用init,否则不会调用init,可以手动调用
		# cls.__init__(new, *args, **kwargs)
		return new

	def __init__(self, *args, **kwargs):
		print('init')

super

  • 与c++不同,python允许不构造父类
class parent:
    def __init__(self):
        print('parent')
    def func(self):
         print('pfunc')
         
class son(parent):
    def __init__(self):
        super(son,self).__init__()
        print('son')
    def func(self):
        print('sfunc')

s=son()
s.func()
super(son,s).func()

类方法@classmethod

class C:
    def __init__(self, *args, **kwargs):
    	print(init)
    	
    # cls时类本身
    @classmethod
    def out_init(cls, *args, **kwargs):
        return cls(*args, **kwargs)

静态方法@staticmethod

class C:
    @staticmethod
    def sta_func():
        print('sta_func')

元类

  • type(name, bases, dict)
  • 设置的均为类属性
func=lambda x:print('i am func')
C = type('C',(object,),{'num':0,'func':func})

c=C()
c.func()
print([x for x in dir(c) if not x.endswith('__')])

设计模式

单例

  • 实例用同一个内存
class Foo:  # 单例模式
    __v=None
    
    @classmethod
    def ge_instance(cls):
        if cls.__v:
            return cls.__v
        else:
            cls.__v=Foo()
            return cls.__v
            
obj1=Foo.ge_instance()
print(obj1)
obj2=Foo.ge_instance()
print(obj2)
obj3=Foo.ge_instance()
print(obj3)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值