zoukankan      html  css  js  c++  java
  • Python学习系列之类属性、类方法和静态方法(二十五)

    类属性、类方法和静态方法

    类属性:类中的方法外的变量称为类属性,被该类的所有对象所共享

    类方法:使用@classmethod修饰的方法,使用类名直接访问的方法

    静态方法:使用@staticmethod修饰的方法,使用类名直接访问的方法

    代码举例:

    • 类属性的使用方式:
    class Student:
        native_pace='吉林'    #直接写在类里的变量,称为类属性
        def __init__(self,name,age):
            self.name=name      #self.name 称为实体属性,进行了一个赋值的操作
            self.age = age
    
        #实例方法
        def eat(self):
            print('学生在吃饭...')
    
        #静态方法
        @staticmethod
        def method():
            print('我使用了statticmethod进行修饰,所以我是静态方法')
    
        #类方法
        @classmethod
        def cm(cls):
            print('我是类方法,因为我使用了classmethod进行修饰')
    
    #类属性的使用方式
    print(Student.native_pace)
    stu1=Student('张三',20)
    stu2=Student('李四',30)
    print(stu1.native_pace)
    print(stu2.native_pace)
    print('-------------')
    Student.native_pace='北京'
    print(stu1.native_pace)
    print(stu2.native_pace)
    

      执行结果:

      说明:类属性可以使用类名调用也可以使用类对象进行调用,当修改该属性的内容时,调用结果也会随着属性的改变而改变

    类方法的使用方式

      

    class Student:
        native_pace='吉林'    #直接写在类里的变量,称为类属性
        def __init__(self,name,age):
            self.name=name      #self.name 称为实体属性,进行了一个赋值的操作
            self.age = age
    
        #实例方法
        def eat(self):
            print('学生在吃饭...')
    
        #静态方法
        @staticmethod
        def method():
            print('我使用了statticmethod进行修饰,所以我是静态方法')
    
        #类方法
        @classmethod
        def cm(cls):
            print('我是类方法,因为我使用了classmethod进行修饰')
    
    #类方法的使用方式
    Student.cm()
    

      执行结果:

      说明:类方法是用类名直接进行调用,类方法的参数cls可以补用填写

    • 静态方法的使用方式
    class Student:
        native_pace='吉林'    #直接写在类里的变量,称为类属性
        def __init__(self,name,age):
            self.name=name      #self.name 称为实体属性,进行了一个赋值的操作
            self.age = age
    
        #实例方法
        def eat(self):
            print('学生在吃饭...')
    
        #静态方法
        @staticmethod
        def method():
            print('我使用了statticmethod进行修饰,所以我是静态方法')
    
        #类方法
        @classmethod
        def cm(cls):
            print('我是类方法,因为我使用了classmethod进行修饰')
    
    # 静态方法的使用方式
    Student.method()
    

      执行结果:

      说明:静态方法的调用使用类名进行调用,静态方法没有参数

  • 相关阅读:
    [Angular] Using the platform agnostic Renderer & ElementRef
    [HTML5] Focus management using CSS, HTML, and JavaScript
    [TypeScript] Increase TypeScript's type safety with noImplicitAny
    [React] displayName for stateless component
    [Redux] Important things in Redux
    [HTML5] Using the tabindex attribute for keyboard accessibility
    [Angular] @ViewChild and template #refs to get Element Ref
    [Angular] @ViewChildren and QueryLists (ngAfterViewInit)
    [Angular] Difference between Providers and ViewProviders
    [Angular] Difference between ngAfterViewInit and ngAfterContentInit
  • 原文地址:https://www.cnblogs.com/wx170119/p/14469122.html
Copyright © 2011-2022 走看看