Starfruit Python Basic Tutorial-Chapter 8: Python Classes and Objects (6) Class Methods, Class Attributes, Static Methods

My CSDN blog column: https://blog.csdn.net/yty_7
Github address: https://github.com/yot777/Python-Primary-Learning

 

8.6 Class methods and instance methods

In the previous part of this chapter, after we defined a class, we instantiated objects of this class and then called methods in the class. This is called instance method .

In fact, there are methods that a class can call directly without instantiating an object. This is called a class method .

Class methods need to be decorated with @classmethod

Instances can call instance methods and class methods, but classes can only call class methods.

 

Examples of Python class methods :

class Animal():
#实例方法
  def __init__(self):      #实例方法的默认参数是self
    #实例属性
    self.name="小花"
  def test1(self):
    print(self.name)
  #类方法需要加上装饰器
  @classmethod         
  def test2(cls):           #类方法的默认参数是cls
    cls.num=100
    print(cls.num)

cat=Animal()               #Animal类的实例化对象cat
cat.test1()                   #实例可以调用实例方法test1
#Animal.test1()           #类不能调用实例方法test1
cat.test2()                   #实例可以调用类方法test2
Animal.test2()             #类可以调用类方法test2

运行结果:
小花
100
100

8.7 Class attributes and instance attributes

The attributes defined in the class are placed in the constructor def __init __ () , called instance attributes .

Placed outside the constructor, it is called a class attribute .

Instances can access instance attributes and class attributes, but classes can only access class attributes.

Class attributes have an important feature: they can be shared between different instance objects , which is similar to global variables in Java .

 

Examples of Python class attributes:

class Person():
  #类属性
  num=0
  def __init__(self,name):
    self.name=name
    n=0
    n+=1               #实例属性每次调用会从初始的值开始
    Person.num+=1      #类属性每次调用会保留上次调用的值,类属性的调用要加类名
    print("name=",name)
    print("n=",n)
    print("Person.num=",Person.num) 

a=Person("小明")
b=Person("小陈")
c=Person("小李") 

运行结果:
name= 小明
n= 1
Person.num= 1
name= 小陈
n= 1
Person.num= 2
name= 小李
n= 1
Person.num= 3

Examples of Java global variables:

//Person类
public class Person {
  public static int num=0;
  public String name;
  public int n;

  public void Person(String name) {
    this.name = name;
    n=0;
    n=n+1;
    num=num+1;
    System.out.println("name="+this.name);
    System.out.println("n="+n);
    System.out.println("Person.num="+num);
  }
}

//PersonTest类
public class PersonTest {
  public static void main(String[] args) {
    Person a = new Person();
    a.Person("小明");
    Person b = new Person();
    b.Person("小陈");
    Person c = new Person();
    c.Person("小李");
  }
}

运行结果:
name=小明
n=1
Person.num=1
name=小陈
n=1
Person.num=2
name=小李
n=1
Person.num=3

8.8 Static methods

Static methods are functions in classes, and no instances are required.

Static methods are mainly used to store logical code, which belongs to the class logically, but has nothing to do with the class itself, that is to say, in the static method, it will not involve the properties and method operations in the class. Static methods cannot call properties and methods in the class.

Static methods need to add decorator @staticmethod

 

Examples of Python static methods :

import time

class TimeTest():
  def __init__(self, hour, minute, second):
    self.hour = hour
    self.minute = minute
    self.second = second

  #普通方法
  def showTime(self):
    print('%s:%s:%s' %(self.hour,self.minute,self.second))

  #静态方法需要加上装饰器
  @staticmethod
  def showCurrentTime():
    return time.strftime("%H:%M:%S", time.localtime())

t = TimeTest(22, 15, 10)
t.showTime()
print(TimeTest.showCurrentTime())

运行结果:
22:15:10
16:01:21

Reference tutorial:

Liao Xuefeng's Python tutorial

https://www.liaoxuefeng.com/wiki/1016959663602400

Liao Xuefeng's Java tutorial

https://www.liaoxuefeng.com/wiki/1252599548343744

Python3 Tutorial | Rookie Tutorial
https://www.runoob.com/python3/
 

If you think this chapter is helpful to you, welcome to follow, comment and like! Github welcomes your Follow and Star!
 

Published 55 original articles · won praise 16 · views 6111

Guess you like

Origin blog.csdn.net/yty_7/article/details/104225915