python类class和静态方法小例

1、代码

#!/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、运行结果

1. init---shanghai
只要调用类就会执行一次
2. name:Wangwang,age:18, cls_city:shanghai
3. [静态方法]:g_country:earth, x_var:serena,不能调用self.name
3. [静态方法]:g_country:earth, x_var:serena,不能调用self.name
4. [类方法]:cls_city:cn,不能调用self.name

你可能感兴趣的:(python,python,linux,前端)