Small example of python class class and static method

1. Code

#!/usr/bin/env python
# -*- coding:utf-8 -*-

g_country = 'earth'


class AnimalClass(object):
    cls_country = 'cn'
    cls_city = 'shanghai'
    print(f"1. init---{cls_city}")

    def __init__(self, name, age):  # 构造函数,类实例化是自动执行
        self.name = name
        self.age = age
        print("只要调用类就会执行一次")

    def getInfo(self):
        print(f'2. name:{self.name},age:{self.age}, cls_city:{self.cls_city}')

    @staticmethod
    def my_static_method(x_var):
        print(f'3. [静态方法]:g_country:{g_country}, x_var:{x_var},不能调用self.name')

    @classmethod
    def my_class_method(cls):
        print(f'4. [类方法]:cls_city:{cls.cls_country},不能调用self.name')


ac1 = AnimalClass('Wangwang', 18)
ac1.getInfo()
ac1.my_static_method('serena')
AnimalClass.my_static_method('serena')
ac1.my_class_method()

2. Running results

1. init---shanghai
will be executed once as long as the class is called
2. name: Wangwang, age: 18, cls_city: shanghai
3. [Static method]: g_country: earth, x_var: serena, cannot call self.name
3. [ Static method]: g_country:earth, x_var:serena, cannot call self.name
4. [Class method]: cls_city:cn, cannot call self.name

Guess you like

Origin blog.csdn.net/xoofly/article/details/131985085