1. <source id="nejs2"></source>
  2. <video id="nejs2"></video>
    <source id="nejs2"></source>
          1. 首頁 > Python 教程 > Python 面向對象 > 在 Python 中使用@staticmethod裝飾器定義靜態方法

            在 Python 中使用@staticmethod裝飾器定義靜態方法

            更新:

            @staticmethod是一個內置的裝飾器,它在 Python 的類中定義了一個靜態方法。 靜態方法不接收任何引用參數,無論它是由類的實例調用還是由類本身調用。

            @staticmethod 特性

            • 在類中聲明靜態方法。
            • 它不能有clsself參數。
            • 靜態方法無法訪問類屬性或實例屬性。
            • 靜態方法可以使用ClassName.MethodName()調用,也可以使用object.MethodName()調用。
            • 它可以返回類的對象。

            下面的示例演示如何在類中定義靜態方法:

            Example: Define Static Method

            class Student:
                name = 'unknown' # class attribute
            
                def __init__(self):
                    self.age = 20  # instance attribute
            
                @staticmethod
                def tostring():
                    print('Student Class') 

            上面,Student類使用@staticmethod裝飾器將tostring()方法聲明為靜態方法。 注意不能有selfcls參數。

            靜態方法可以使用ClassName.MethodName()object.MethodName()調用,如下圖所示。

            Example: Calling Class Method using Object

            >>> Student.tostring()
            'Student Class'
            >>> Student().tostring() 
            'Student Class'
            >>> std = Student()
            >>> std.tostring()
            'Student Class' 

            靜態方法無法訪問類屬性或實例屬性。如果嘗試這樣做,將會引發錯誤。

            Example: Static Method

            class Student:
                name = 'unknown' # class attribute
            
                def __init__(self):
                    self.age = 20  # instance attribute
            
                @staticmethod
                def tostring():
                    print('name=',name,'age=',self.age) 

            當您調用上面的靜態方法時,下面將是輸出。

            >>> Student.tostring()
            Traceback (most recent call last):
              File "<pyshell#22>", line 1, in <module>
                Student.tostring()
              File "<pyshell#21>", line 7, in display
                print('name=',name,'age=',self.age)
            NameError: name 'name' is not defined 

            @classmethod vs @staticmethod

            下表列出了類方法與靜態方法的區別:

            @classmethod @staticmethod
            聲明一個類方法。 聲明一個靜態方法。
            它可以訪問類屬性,但不能訪問實例屬性。 它不能訪問類屬性或實例屬性。
            可以使用ClassName.MethodName()object.MethodName()來調用。 可以使用ClassName.MethodName()object.MethodName()來調用。
            它可以用來聲明返回類對象的工廠方法。 它可以返回類的對象。
            頂部 久久久久99精品成人片毛片_黃色A片三級三級三級无码_日本不卡高清视频v中文字幕_高清欧美视频一区二区
            1. <source id="nejs2"></source>
            2. <video id="nejs2"></video>
              <source id="nejs2"></source>