Python-高级:类对象、实例对象、类方法、实例方法、类属性、实例属性、静态方法

参考教程的截图: 

Python-高级:类对象、实例对象、类方法、实例方法、类属性、实例属性、静态方法_第1张图片

示例代码:


class Test():

    company = 'OTN'

    # 实例方法
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __str__(self):
        return "name is {}, age is {}".format(self.name, self.age)

    def foo(self):
        print("foo :", self.name, self.age)

    # 类方法
    @classmethod
    def change_company(cls, company):
        cls.company = company
    
    @classmethod
    def print_company(cls):
        print(cls.company)
    
    # 静态方法
    @staticmethod
    def asdf():
        print("我就是一个静态方法。")

test = Test('lili', 12)
print(test)
test.foo()
print("查看类属性", test.company)
test.company = 'QWE'
print("将类属性改为QWE,查看是否更改:")
print("test.company:", test.company)
print("Test.company:", Test.company)

print("*"*20)

print("用类方法更改类属性:")
Test.change_company('CFR')
Test.print_company()
Test.asdf()

运行结果:

Python-高级:类对象、实例对象、类方法、实例方法、类属性、实例属性、静态方法_第2张图片

原理图:

Python-高级:类对象、实例对象、类方法、实例方法、类属性、实例属性、静态方法_第3张图片

 

你可能感兴趣的:(Python)