類函數第一參數爲類,實例函數第一個參數爲實例

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 代表當前對象的引用,可以通過此函數,來實現想要的查詢 / 修改類的屬性等功能

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章