Python 笔记(14)— 类对象及属性内置方法 classmethod、delattr、dir、hasattr、getattr、callable

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 对象,比如函数 strint 等都是可被调用的。

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)

如果 classclassinfo 类的子类,返回 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) #直接调用父类的add方法
    ...:         print(r) #子类的add与父类相比,能实现对结果的打印功能
    ...:

In [3]: Son(1).add(2)
3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值