classmethod可以来调用类的属性,类的方法,实例化对象

本文介绍了Python中classmethod的用法,包括如何通过classmethod调用类的属性、方法和实例化对象。同时,文章还提及了compile()、delattr()、dict()、dir()、divmod()等其他内置函数的使用示例。

classmethod可以来调用类的属性,类的方法,实例化对象,今天番茄加速就来讲一下。在这里插入图片描述

classmethod()

classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

In [66]: class Student():

…: def init(self,id,name):

…: self.id = id

…: self.name = name

…: def repr(self):

…: return 'id = ‘+self.id +’, name = '+self.name

…: @classmethod

…: def f(cls):

…: print(cls)

complie()

将字符串编译成python 能识别或可以执行的代码,也可以将文字读成字符串再编译。

In [74]: s = “print(‘helloworld’)”

In [75]: r = compile(s,"", “exec”)

In [76]: r

Out[76]: at 0x0000000005DE75D0, file “”, line 1>

In [77]: exec®

helloworld

complex()

创建一个复数

In [81]: complex(1,2)

Out[81]: (1+2j)

delattr()

删除对象的属性

In [87]: delattr(xiaoming,‘id’)

In [88]: hasattr(xiaoming,‘id’)

Out[88]: False

dict()

创建数据字典

In [92]: dict()

Out[92]: {}

In [93]: dict(a=‘a’,b=‘b’)

Out[93]: {‘a’: ‘a’, ‘b’: ‘b’}

In [94]: dict(zip([‘a’,‘b’],[1,2]))

Out[94]: {‘a’: 1, ‘b’: 2}

In [95]: dict([(‘a’,1),(‘b’,2)])

Out[95]: {‘a’: 1, ‘b’: 2}

dir()

不带参数时返回当前范围内的变量,方法和定义的类型列表;带参数时返回参数的属性,方法列表。

In [96]: dir(xiaoming)

Out[96]:

[‘class’,

delattr’,

dict’,

dir’,

doc’,

eq’,

format’,

ge’,

getattribute’,

gt’,

hash’,

init’,

init_subclass’,

le’,

lt’,

module’,

ne’,

new’,

reduce’,

reduce_ex’,

repr’,

setattr’,

sizeof’,

str’,

subclasshook’,

weakref’,

‘name’]

divmod()

分别取商和余数

In [97]: divmod(10,3)

Out[97]: (3, 1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值