类的特殊成员


__init__()

构造方法:通过类创建对象时,自动触发执行。

class Example(object):
    def __init__(self):
        print("创建类时自动执行。")
        
a = Example()

>>>创建类时自动执行。

__call__()

表示当前操作的对象的类是什么

class Example(object):
    def __init__(self):
        print("创建类时自动执行。")
    def __call__(self):
        print("这是Example类")

a = Example()
a()

>>>创建类时自动执行。
>>>这是Example类

__int__()

当执行 int(对象) 时,自动调用 __int__() 方法

class Example(object):
    def __init__(self):
        pass

    def __int__(self):
        print("调用int(对象)时自动调用")
        return 1

a = Example()
print(int(a))

>>> 调用int(对象)时自动调用
>>> 1

__str__()

如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。

class Example(object):
    def __init__(self):
        pass

    def __str__(self):
        print("调用str(对象)时自动调用")
        return "这是Example类"

a = Example()
print(str(a))

>>> 调用str(对象)时自动调用
>>> 这是Example类

但大部分情况下都不是这么使用的。以下打印时,得到一个地址和类名,但是根本不知道这个类的有用信息。

 
 

class Example(object):
  def __init__(self,name,age):
    self.name = name
    self.age = age

a = Example("dongye",18)
print(a)

>>> <__main__.Example object at 0x00000000029ED5C0>

这时候,需要在内部有个__str__方法。

class Example(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __str__(self):
        return ("name = %s, age = %d" %(self.name,self.age,))

a = Example("dongye",18)
print(a)

>>>name = dongye, age = 18

其实,当你调用 print(a) 时,自动变成 print(str(a)) ,然后自动去寻找 a 中的 __str__。

__add__()

当你想要让两个 类对象 相加的时候使用。如果没有 __add__() 方法,会报错。

class Example(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __add__(self,other):
        return ("a对象 + b对象的和。结果为 a对象的 __add__。")

a = Example("dongye",18)
b = Example("dongye2",28)
print(a+b)

>>> a对象 + b对象的和。结果为 a对象的 __add__

要注意,__add__() 方法有两个参数。self 表示对象自己,other 表示要相加的第二个对象。

class Example(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __add__(self,other):
        return (self.age + other.age)

a = Example("dongye",18)
b = Example("dongye2",28)
print(a+b)

>>> 46

猜你喜欢

转载自www.cnblogs.com/dongye95/p/9032017.html