Python3特殊函数__init__();__new__();__call__();__str__()

__init__()

这个方法一般用于初始化一个类
但是 当实例化一个类的时候, __init__并不是第一个被调用的, 第一个被调用的是__new__

__new__()

  • __new__方法是创建类实例的方法, 创建对象时调用, 返回当前对象的一个实例
  • __init__方法是类实例创建之后调用, 对当前对象的实例的一些初始化, 没有返回值

__call__()

对象通过提供一个__call__(self, *args, *kwargs)方法可以模拟函数的行为, 如果一个对象提供了该方法, 可以向函数一样去调用它

__str__()

这是一个内置方法, 只能返回字符串, 并且只能有一个参数self

class Person(object):

    def __init__(self,name,age,height):
        print("Object __init__")
        self.name = name
        self.age = age
        self.height = height

    #静态方法
    @staticmethod
    def __new__(cls,name,age,height):
        print ("Object __new__")
        return super(Person, cls).__new__(cls)  #返回为类对象,如果没有返回将不会调用__init__.

    def introduce(self):
        print("Person name is %s, age is %s, and height is %s" % (self.name, self.age, self.height))

    def __call__(self, *args, **kwargs):
        print ("Object __call__")
        self.name = kwargs["name"]
        self.age = kwargs["age"]
        self.introduce()

    def __str__(self):
        print ("Object __str__")
        return "Person name is %s, age is %s, and height is %s" % (self.name, self.age, self.height)


print("Class Per" + "=" * 40)
p1 = Person("1111","222","333")
p1.introduce()
p1(name="1",age="2")
print(p1)

 result

Class Per========================================
Object __new__
Object __init__
Person name is 1111, age is 222, and height is 333
Object __call__
Person name is 1, age is 2, and height is 333
Object __str__
Person name is 1, age is 2, and height is 333
原文地址:https://www.cnblogs.com/desultory-essay/p/13473916.html