面向对象的一些方法与属性

常用

常用属性

obj.__calss__ # 查看对象的类
class.__name__ # 类的名字
class.__bases__ # 类的父类
class.__mro__ # 该类实例调用方法的查找顺序

基本方法

__new__(cls[, ...])

1. __new__ 是在一个对象实例化的时候所调用的第一个方法
2. 它的第一个参数是这个类,其他的参数是用来直接传递给 __init__ 方法
3. __new__ 决定是否要使用该 __init__ 方法,因为 __new__ 可以调用其他类

的构造方法或者直接返回别的实例对象来作为本类的实例,如果 __new__

没有返回实例对象,则 __init__ 不会被调用

4. __new__ 主要是用于继承一个不可变的类型比如一个 tuple 或者 string

__init__(self[, ...])

构造器,当一个实例被创建的时候调用的初始化方法,

主要用来为实例设置属性

__del__(self)

析构器,当一个实例被销毁的时候调用的方法

__call__(self[, args...])

实例被调用时执行的方法

__len__(self)

定义当被 len() 调用时的行为

__repr__(self)

定义当被 repr() 调用时的行为

__str__(self)

定义当被 str() 调用时的行为,如果一个类中没定义__str__,定义了__repr__,str()会去执行__repr__

__bytes__(self)

定义当被 bytes() 调用时的行为

__hash__(self)

定义当被 hash() 调用时的行为

__bool__(self)

定义当被 bool() 调用时的行为,应该返回 True 或 False.在python的一些对象中True和False会根据len()来判断.

__format__(self, format_spec)

定义当被 format() 调用时的行为

与属性相关的魔法方法

__getattr__(self, name)

定义当用户试图获取一个不存在的属性时的行为

__getattribute__(self, name)

定义当该类的属性被访问时的行为

__setattr__(self, name, value)

定义当一个属性被设置时的行为

当你定义了此方法时一定要注意__init__()中的为属性赋值

例:

class Local(object):

    def __init__(self):
        # 如果直接self.storage = {},就会出现循环调用
        object.__setattr__(self,‘storage‘,{})

    def __setattr__(self, k, v):
        ident = get_ident()
        if ident in self.storage:
            self.storage[ident][k] = v
        else:
            self.storage[ident] = {k: v}

    def __getattr__(self, k):
        ident = get_ident()
        return self.storage[ident][k]     

__delattr__(self, name)

定义当一个属性被删除时的行为

__dir__(self)

定义当 dir() 被调用时的行为,此方法返回类或对象的所有属性及方法名

class aa:
    a = 1
    b = 2
    def c(self):
        pass

d = dir(aa)
c = aa()
c.e = 11
f = dir(c)
print(set(d)^set(f)) # {‘e‘}
print(d)
print(f)

__get__(self, instance, owner)

如果class定义了它,则这个class就可以称为descriptor(描述符)。owner是所有者的类,instance是访问descriptor的实例,如果不是通过实例访问,而是通过类访问的话,instance则为None。(descriptor的实例自己访问自己是不会触发__get__,而会触发__call__,只有descriptor作为其它类的属性才有意义。)

例:

class C(object):
    a = ‘abc‘

    def __getattribute__(self, *args, **kwargs):
        print("__getattribute__() is called")
        return object.__getattribute__(self, *args, **kwargs)

    #    return "haha"
    def __getattr__(self, name):
        print("__getattr__() is called ")
        return name + " from getattr"

    def __get__(self, instance, owner):
        print("__get__() is called", instance, owner)
        return self

    def foo(self, x):
        print(x)

class C2(object):
    d = C()
if __name__ == ‘__main__‘:
    c = C()
    c2 = C2()
    c.a # __getattribute__() is called
    c2.d  # __get__() is called <__main__.C2 object at 0x000001BA4EBFBB00> <class ‘__main__.C2‘>

__set__(self, instance, value)

定义当描述符的值被改变时的行为

__delete__(self, instance)

定义当描述符的值被删除时的行为

上下文管理语句

__enter__(self)

1. 定义当使用 with 语句时的初始化行为
2. __enter__ 的返回值被 with 语句的目标或者 as 后的名字绑定

__exit__(self, exc_type, exc_value, traceback)

1. 定义当一个代码块被执行或者终止后上下文管理器应该做什么
2. 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作

  这里有更多

容器类型

__len__(self)

定义当被 len() 调用时的行为(返回容器中元素的个数)

__getitem__(self, key)

定义获取容器中指定元素的行为,相当于 self[key]

__setitem__(self, key, value)

定义设置容器中指定元素的行为,相当于 self[key] = value

__delitem__(self, key)

定义删除容器中指定元素的行为,相当于 del self[key]

__iter__(self)

定义当迭代容器中的元素的行为, 比如for循环这个对象

__reversed__(self)

定义当被 reversed() 调用时的行为

__contains__(self, item)

定义当使用成员测试运算符(in 或 not in)时的行为

不常用

比较操作符

__lt__(self, other) 定义小于号的行为:x < y 调用 x.__lt__(y)
__le__(self, other) 定义小于等于号的行为:x <= y 调用 x.__le__(y)
__eq__(self, other) 定义等于号的行为:x == y 调用 x.__eq__(y)
__ne__(self, other) 定义不等号的行为:x != y 调用 x.__ne__(y)
__gt__(self, other) 定义大于号的行为:x > y 调用 x.__gt__(y)
__ge__(self, other) 定义大于等于号的行为:x >= y 调用 x.__ge__(y)

算数运算符

_add__(self, other) 定义加法的行为:+
__sub__(self, other) 定义减法的行为:-
__mul__(self, other) 定义乘法的行为:*
__truediv__(self, other) 定义真除法的行为:/
__floordiv__(self, other) 定义整数除法的行为://
__mod__(self, other) 定义取模算法的行为:%
__divmod__(self, other) 定义当被 divmod() 调用时的行为
__pow__(self, other[, modulo]) 定义当被 power() 调用或 ** 运算时的行为
__lshift__(self, other) 定义按位左移位的行为:<<
__rshift__(self, other) 定义按位右移位的行为:>>
__and__(self, other) 定义按位与操作的行为:&
__xor__(self, other) 定义按位异或操作的行为:^
__or__(self, other) 定义按位或操作的行为:|

反运算

__radd__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rsub__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rmul__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rtruediv__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rfloordiv__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rmod__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rdivmod__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rpow__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rlshift__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rrshift__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__rxor__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
__ror__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)

增量赋值运算

__iadd__(self, other) 定义赋值加法的行为:+=
__isub__(self, other) 定义赋值减法的行为:-=
__imul__(self, other) 定义赋值乘法的行为:*=
__itruediv__(self, other) 定义赋值真除法的行为:/=
__ifloordiv__(self, other) 定义赋值整数除法的行为://=
__imod__(self, other) 定义赋值取模算法的行为:%=
__ipow__(self, other[, modulo]) 定义赋值幂运算的行为:**=
__ilshift__(self, other) 定义赋值按位左移位的行为:<<=
__irshift__(self, other) 定义赋值按位右移位的行为:>>=
__iand__(self, other) 定义赋值按位与操作的行为:&=
__ixor__(self, other) 定义赋值按位异或操作的行为:^=
__ior__(self, other) 定义赋值按位或操作的行为:|=

一元操作符

__neg__(self) 定义正号的行为:+x
__pos__(self) 定义负号的行为:-x
__abs__(self) 定义当被 abs() 调用时的行为
__invert__(self) 定义按位求反的行为:~x

类型转换

__complex__(self)

定义当被 complex() 调用时的行为(需要返回恰当的值)

__int__(self)

定义当被 int() 调用时的行为(需要返回恰当的值)

__float__(self)

定义当被 float() 调用时的行为(需要返回恰当的值)

__round__(self[, n])

定义当被 round() 调用时的行为(需要返回恰当的值)

__index__(self)

1. 当对象是被应用在切片表达式中时,实现整形强制转换
2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 __index__
3. 如果 __index__ 被定义,则 __int__ 也需要被定义,且返回相同的值

原文地址:https://www.cnblogs.com/wwg945/p/8977340.html

时间: 2024-08-07 09:52:36

面向对象的一些方法与属性的相关文章

面向对象之类的方法 私有属性(加俩下划线) 新式类 经典类的区别

@classmetod #!/usr/bin/env python # -*- coding:utf-8 -*- class Animal: def __init__(self,name): self.name = name hobbie = 'meat' @classmethod #类方法不能访问实例变量 加上后 self.name就无法访问了 def talk(self): #print("%s is talking" %self.name) print("%s is t

面向对象 字段、方法、属性

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02面向对象复习 { class Program { static void Main(string[] args) { Person p = new Person(); p.Age = -110; p.Name = "zhangsan"

Objective-C语言介绍 、 Objc与C语言 、 面向对象编程 、 类和对象 、 属性和方法 、 属性和实例变量

Objective-C语言介绍 . Objc与C语言 . 面向对象编程 . 类和对象 . 属性和方法 . 属性和实例变量 1 第一个OC控制台程序 1.1 问题 Xcode是苹果公司向开发人员提供的集成开发环境(非开源),用于开发Mac OS X,iOS的应用程序.其运行于苹果公司的Mac操作系统下. 本案例要求使用集成开发工具Xcode编写OC的HelloWorld程序,在Xcode的控制台中, 1.2 方案 首先,启动集成开发工具Xcode. 然后,创建OC语言的工程. 最后,运行所创建的工

Python面向对象高级编程:@property--把方法变为属性

为了限制score的范围,可以通过一个set_score()方法来设置成绩,再通过一个get_score()来获取成绩,这样,在set_score()方法里,就可以检查参数: 1 >>> class Student(object): 2 def get_score(self): 3 return self.__score 4 def set_score(self,value): 5 if not isinstance(value,int): 6 raise ValueError('sec

Python面向对象静态方法,类方法,属性方法

静态方法(staticmethod名义上归类管理,实际上在静态方法里访问不到类或实例中的静态属性) 1 class days(object): 2 def __init__(self, food): 3 self.food = food 4 5 @staticmethod # 实际和类没有关系 6 def tell(self): 7 print('这里有%s,%s快来' % (self.food, 'name')) 8 9 10 a = days('香蕉') 11 a.tell(a) 类方法(c

Python基础教程(第九章 魔法方法、属性和迭代器)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5437223.html______ Created on Marlowes 在Python中,有的名称会在前面和后面都加上两个下划线,这种写法很特别.前面几章中已经出现过一些这样的名称(如__future__),这种拼写表示名字有特殊含义,所以绝不要在自己的程序中使用这样的名字.在Python中,由这些名字组成的集合所包含的方法称

面向对象的思维方法

我是从学习Java编程开始接触OOP(面向对象编程),刚开始使用Java编写程序的时候感觉很别扭,因为我早以习惯用C来编写程序,很欣赏C的简洁性和高效性,喜欢C简练而表达能力丰富的风格,特别忍受不了Java运行起来慢吞吞的速度,相对冗长的代码,而且一个很简单的事情,要写好多类,一个类调用一个类,心里的抵触情绪很强. 我对Java的面向对象的特性琢磨良久,自认为有所领悟,也开始有意识的运用OOP风格来写程序,然而还是经常会觉得不知道应该怎样提炼类,面对一个具体的问题的时候,会觉得脑子里千头万绪的,

EXTJS4自学手册——EXT基本方法、属性(mixins多继承、statics、require)

1.mixins 说明:类似于面向对象中的多继承 <script type="text/javascript"> Ext.onReady(function () {//创建一个类,类名:TextClass,具有两个属性:A.B Ext.define('TextClass', { A: 'a', B: 'b' });//创建一个类,类名:TextClass,具有两个属性:A.B Ext.define('TextClass2', { C: 'c', write: functio

面向对象中特殊方法的补充、isinstance/issubclass/type、方法和函数、反射

一.面向对象中特殊方法的补充 1.__str__ 能将对象名改成你想要的字符串,但是类型还是类 class Foo(object): def __init__(self): pass def func(self): pass def __str__(self): return "f1" obj = Foo() print(obj,type(obj)) # f1 <class '__main__.Foo'> 2.__doc__ 能将类的注释文档显示出来 class Foo(o