Python 类对象及属性内置方法 classmethod、delattr、dir、hasattr、getattr、callable
生活随笔
收集整理的這篇文章主要介紹了
Python 类对象及属性内置方法 classmethod、delattr、dir、hasattr、getattr、callable
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. classmethod
classmethod 修飾符對應(yīng)的函數(shù)不需要實(shí)例化,不需要 self 參數(shù)。第一個(gè)參數(shù)需要是表示自身類的 cls 參數(shù),能調(diào)用類的屬性、方法、實(shí)例等。
class People(object):def __init__(self, number, name):self.number = numberself.name = namedef instance_method(self):print("This is instance method")return self@classmethoddef class_method(cls):print("This is class method")return cls@classmethoddef print_class_info(cls):print("類名為 {}".format(cls.__name__))People.class_method()
People.print_class_info()
2. delattr(object, name)
刪除對象的屬性,在不需要某個(gè)或某些屬性時(shí),這個(gè)方法就會(huì)很有用。
In [1]: class People(object):...: def __init__(self, number, name):...: self.number = number...: self.name = name...: In [2]: wohu = People(1, "wohu")In [3]: delattr(wohu, 'number')In [4]: wohu.number
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-d950a0aab65b> in <module>
----> 1 wohu.numberAttributeError: 'People' object has no attribute 'number'In [5]: hasattr(wohu, 'number')
Out[5]: FalseIn [6]: hasattr(wohu, 'name')
Out[6]: True
3. dir([object])
不帶參數(shù)時(shí),返回當(dāng)前范圍內(nèi)的變量、方法和定義的類型列表;帶參數(shù)時(shí)返回參數(shù)的屬性、方法列表。
In [7]: dir(wohu)
Out[7]:
['__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']
4. hasattr(object, name)
判斷對象是否有某個(gè)屬性
In [5]: hasattr(wohu, 'number')
Out[5]: FalseIn [6]: hasattr(wohu, 'name')
Out[6]: True
5. getattr(object, name[, default])
獲取對象的屬性:
In [8]: getattr(wohu, 'name')
Out[8]: 'wohu'
6. callable(object)
判斷對象是否可被調(diào)用,能被調(diào)用的對象就是一個(gè) callable 對象,比如函數(shù) str 、 int 等都是可被調(diào)用的。
In [9]: callable(int)
Out[9]: TrueIn [10]: callable(str)
Out[10]: True
如下代碼,默認(rèn)實(shí)例化對象是不可調(diào)用的,
In [12]: class People(object):...: def __init__(self, number, name):...: self.number = number...: self.name = name...: In [13]: wohu = People(1, "wohu")In [14]: callable(wohu)
Out[14]: False
如果想要讓實(shí)例化對象能調(diào)用,如 wohu() 則需要增加 __call__ 方法:
In [15]: class People(object):...: def __init__(self, number, name):...: self.number = number...: self.name = name...: def __call__(self):...: print("can be called")...: print("my name is {}".format(self.name))...: In [16]: wohu = People(1, "wohu")In [17]: callable(wohu)
Out[17]: TrueIn [18]: wohu()
can be called
my name is wohu
總結(jié)
以上是生活随笔為你收集整理的Python 类对象及属性内置方法 classmethod、delattr、dir、hasattr、getattr、callable的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求一个酷一点的个性签名。
- 下一篇: Python 是一门动态的、强类型语言