zoukankan      html  css  js  c++  java
  • 类函数第一参数为类,实例函数第一个参数为实例

    node2:/tmp/20200608#cat Entity.py
    class Document():
      WELCOME_STR = 'Welcome! The context for this book is {}.'
      @classmethod    
      def create_empty_book(cls, title, author):        
           print cls
           return cls(title=title, author=author, context='nothing')
      def get_a(a,b):
        print self;
        return a + b
    	
    
     
     node2:/tmp/20200608#cat Entity.py
    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    class Document():
        
        WELCOME_STR = 'Welcome! The context for this book is {}.'
        
        def __init__(self, title, author, context):
            print('init function called')
            self.title = title
            self.author = author
            self.__context = context
        
        # 类函数
        @classmethod
        def create_empty_book(cls, title, author):
            print '1111111111111111111111'
            print cls
            print '1111111111111111111111'
            return cls(title=title, author=author, context='nothing')
        
        # 成员函数
        def get_context_length(self,a,b):
            print '2222222222222'
            return a+b
        
        # 静态函数
        @staticmethod
        def get_welcome(context):
            return Document.WELCOME_STR.format(context)
    		
    
     node2:/tmp/20200608#cat t1.py 
    from  Entity import *
    a=Document('a','b','c')
    print a
    print type(a)
    print dir(a)
    print a.WELCOME_STR
    b=a.create_empty_book(33,44)
    print b
    print a.get_context_length(55,66)
    
    
    node2:/tmp/20200608#python t1.py 
    init function called
    <Entity.Document instance at 0x7f48bc46ffc8>
    <type 'instance'>
    ['WELCOME_STR', '_Document__context', '__doc__', '__init__', '__module__', 'author', 'create_empty_book', 'get_context_length', 'get_welcome', 'title']
    Welcome! The context for this book is {}.
    
    1111111111111111111111
    Entity.Document
    1111111111111111111111
    
    init function called
    <Entity.Document instance at 0x7f48bc47b050>
    
    2222222222222
    <Entity.Document instance at 0x7f48bc46ffc8>
    121
    
    类函数的第一个参数一般为 cls,表示必须传一个类进来
    
    成员函数则是我们最正常的类的函数,它不需要任何装饰器声明,第一个参数 self 代表当前对象的引用,可以通过此函数,来实现想要的查询 / 修改类的属性等功能
  • 相关阅读:
    Linux之安装python3.6.6
    Python之计算器
    springboot项目快速代码生成工具
    电脑忘记密码怎么办?
    HTML编辑器
    WCF的几种寄宿方式
    获取客户端IP 和 外网IP
    发送短信验证码
    动态库,服务tips
    asp.net WebService 与 WCF的区别
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13348345.html
Copyright © 2011-2022 走看看