1. classmethod
Python
使用关键字 class
定制自己的类,self
表示类实例对象本身。
classmethod
修饰符对应的函数不需要实例化,不需要 self
参数。第一个参数需要是表示自身类的 cls
参数,能调用类的属性、方法、实例等。
class People(object):
def __init__(self, number, name):
self.number = number
self.name = name
def instance_method(self):
print("This is instance method")
return self
@classmethod
def class_method(cls):
print("This is class method")
return cls
@classmethod
def print_class_info(cls):
print("类名为 {}".format(cls.__name__))
People.class_method()
People.print_class_info()
2. delattr
delattr(object, name)
删除对象的属性,在不需要某个或某些属性时,这个方法就会很有用。
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.number
AttributeError: 'People' object has no attribute 'number'
In [5]: hasattr(wohu, 'number')
Out[5]: False
In [6]: hasattr(wohu, 'name')
Out[6]: True
3. hasattr、setattr
hasattr(object, name)
判断对象是否有某个属性
In [5]: hasattr(wohu, 'number')
Out[5]: False
In [6]: hasattr(wohu, 'name')
Out[6]: True
使用 setattr
动态添加对象的属性,函数原型:
<function setattr(obj, name, value, /)>
为类对象 Student
添加属性:
if not hasattr(Student, 'address'):
setattr(Student,'address','beijing')
print(hasattr(s1,'address'))
4. getattr
getattr(object, name[, default])
获取对象的属性:
In [8]: getattr(wohu, 'name')
Out[8]: 'wohu'
5. dir
dir([object])
- 不带参数时,返回当前范围内的变量、方法和定义的类型列表;
- 带参数时返回参数的属性、方法列表;
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']
6. callable(object)
callable(object)
判断对象是否可被调用,能被调用的对象就是一个 callable
对象,比如函数 str
、 int
等都是可被调用的。
In [9]: callable(int)
Out[9]: True
In [10]: callable(str)
Out[10]: True
如下代码,默认实例化对象是不可调用的,
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
如果想要让实例化对象能调用,如 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]: True
In [18]: wohu()
can be called
my name is wohu
7. isinstance
实例属于某个对象判断
isinstance(object, classinfo)
判断 object
是否为类 classinfo
的实例,若是,返回 true
。
In [79]: class Student():
...: def __init__(self,id=None,name=None):
...: self.id = id
...: self.name = name
In [21]: xiaoming = Student('001','xiaoming')
In [22]: isinstance(xiaoming,Student)
Out[22]: True
序列类型的基类为 Iterable
,所以返回 True
。
In [85]: from collections.abc import Iterable
In [84]: isinstance([1,2,3],Iterable)
Out[84]: True
8. issubclass
子类判断
issubclass(class, classinfo)
如果 class
是 classinfo
类的子类,返回 True
:
In [27]: class undergraduate(Student):
...: def studyClass(self):
...: pass
...: def attendActivity(self):
...: pass
...:
In [28]: issubclass(undergraduate,Student)
Out[28]: True
In [29]: issubclass(object,Student)
Out[29]: False
In [30]: issubclass(Student,object)
Out[30]: True
classinfo
取值也可能为元组,若 class
是元组内某个元素类型的子类,也会返回 True
。
In [26]: issubclass(int, (int,float) )
Out[26]: True
9. 鸭子类型
Python
是动态语言,对函数参数的类型要求很宽松,函数体内使用此类型的方法或属性时,只要满足有它们就行,不强制要求必须为这个类或子类。但是,对静态类型语言,如 Java
,参数类型就必须为此类型或子类。
例如,下面定义一个 Plane
类,定义函数 using_run
:
class Plane():
def run(self):
print('plane is flying...')
def using_run(duck):
print(duck.run())
using_run(Plane())
打印结果:
plane is flying...
定义一个 Clock
类,它与 Plane
类没有继承关系,但是也有一个 run
方法:
class Clock():
def run(self):
print('clock is rotating...')
using_run
函数中,同样可传入 Clock
对象:
using_run(Clock())
打印结果:
clock is rotating...
Plane
对象和 Clock
对象,因都有 run
方法, Python
认为它们看起来就是 duck
类型,因此,Plane
对象和 Clock
对象就被看作 duck
类型。
10. super
super([type[, object-or-type]])
返回一个代理对象,它会将方法调用委托给 type 的父类或兄弟类。
如下,子类的 add 方法,一部分直接调用父类 add ,再有一部分个性的行为:打印结果。
In [1]: class Parent():
...: def __init__(self,x):
...: self.v = x
...:
...: def add(self,x):
...: return self.v + x
In [2]: class Son(Parent):
...: def add(self,y):
...: r = super().add(y)
...: print(r)
...:
In [3]: Son(1).add(2)
3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)