V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
fanqieipnet
V2EX  ›  推广

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

  •  
  •   fanqieipnet · 2021-01-08 18:06:11 +08:00 · 604 次点击
    这是一个创建于 1265 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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(r)

       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)
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3713 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 05:19 · PVG 13:19 · LAX 22:19 · JFK 01:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.