python内置方法

概述

首先明确函数和代码的区别,常用的内置方法有 __init__,__str__

详解

函数和方法的区别:

1)函数是没有类面向过程,组织好的、可以重复使用的、用来实现单一功能的代码;

2)方法必须有class类的,调用类里面的函数使用的

内置方法:

__init__,实例创建自动获取这些属性

__str__,print类名直接打印__str__方法里的return内容

__name__, 模块变量名,当前模块是主函数名是__main__可以在__main__里提高代码的健壮性减少bug

__call__,定义类这个类可以当做函数来使用相当于重载

super(),子类函数中使用,作用是继承父类方法

__author__,通过IDE修改文件时的头部文件

__new__,用在实例中,常用在单例模式的实现上

代码

__init__()、__str__()

class Book:

    def __init__(self, name, author, comment, state = 0):
        self.name = name
        self.author = author
        self.comment = comment
        self.state = state

    def __str__(self):
        if self.state == 0:
            status = '未借出'
        else:
            status = '已借出'
        return '名称:《%s》 作者:%s 推荐语:%s
状态:%s ' % (self.name, self.author, self.comment, status)

book = Book('看不见的城市','卡尔维诺','献给城市的最后一首爱情诗','未借出')

#__str__内置方法直接打印Book类里面的__str__方法里面的return内容
print(book)  不能写成print(book.__str__())
#__init__内置方法直接提取Book类里面的__init__方法的属性(参数)
print(book.name)  不能写成print(book.__init__().name)

__name__

1 #Py2.py
2 #!/usr/bin/env python
3 import Py1.py
4 def test():
5   print '__name__ = ',__name__
6 if __name__ == '__main__':
7   test()
8   print ‘Py1.py __name__ = ’,Py1.__name__

执行结果:

__name__=__main__
Py1.py __name__=Py1

__call__()

class Person(object):
    def __init__(self, name, gender):
      self.name = name
      self.gender = gender

    def __call__(self, friend):
      print 'My name is %s...' % self.name
      print 'My friend is %s...' % friend
  现在可以对 Person 实例直接调用:

  >>> p = Person('Bob', 'male')
  >>> p('Tim')
  My name is Bob...
  My friend is Tim...

 super()

class A:
    def add(self,x):
        y = x+1
        print(y)
class B(A):
    def add(self,x):
        super().add(x)#继承父类A().add()方法内容
b = B()
b.add(2)

 __new__()

  1.特性 1)将类自身实例化后调用 2)它始终是静态方法,及时没有加上静态方的法装饰器
  2.和__init__()类似,但__new__()是创建之后调用

#绝对值,__init__() 和 __new__() 比较
class PositiveInteger(int):
    def __init__(self, value):
        super(PositiveInteger, self).__init__(self, abs(value))
i = PositiveInteger(-3)
print i


class PositiveInteger(int):
    def __new__(cls, value):
        return super(PositiveInteger, cls).__new__(cls, abs(value))
i = PositiveInteger(-3)
print i
#单例模式利用__new__()
class Singleton(object):

  def __new__(cls):

    # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象

    if not hasattr(cls, 'instance'):

      cls.instance = super(Singleton, cls).__new__(cls)

    return cls.instance

obj1 = Singleton()

obj2 = Singleton()

obj1.attr1 = 'value1'

print obj1.attr1, obj2.attr1

print obj1 is obj2


输出结果:

value1 value1

True

可以看到obj1和obj2是同一个实例

参考链接

https://www.pypypy.cn/#/apps/1/lecture/5cd9765c19bbcf00015547b2

https://www.pypypy.cn/#/apps/1/practices/5cd9766119bbcf00015547c3

https://www.cnblogs.com/xinglejun/p/10129823.html

https://www.cnblogs.com/bovenson/p/4768142.html

https://www.cnblogs.com/niusha/p/10618493.html

https://www.cnblogs.com/34fj/p/6358702.html

https://zhidao.baidu.com/question/1244202806778972019.html

https://www.runoob.com/python/func-number-abs.html

转载引用请标明出处,本博出自喝了少不如不喝的博客https://home.cnblogs.com/u/wangdadada
原文地址:https://www.cnblogs.com/wangdadada/p/12239984.html