Python中self和cls的区别和使用

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Animal:
    age = 0
    weight = 0

    def __init__(self, species, age, weight):
        self.species = species
        Animal.age = age
        Animal.weight = weight

    def displayAge(self):
        print(self.species + "' age: " + str(Animal.age))
    def displayWeight(self):
        print(self.species + "' weight: " + str(Animal.weight))

    def self_test(self):
        print("Hello: " + str(self))

    def cls_test(cls):
        print("Hello: " + str(cls))


horse = Animal("horse", 10, 100)
horse.displayAge()
horse.displayWeight()

horse.self_test()
horse.cls_test()

#Animal.self_test()   #TypeError: self_test() missing 1 required positional argument: 'self'
#Animal.cls_test()     #TypeError: cls_test() missing 1 required positional argument: 'cls'

Animal.self_test(horse)
Animal.cls_test(Animal)

 

 

/home/zhenglf/PycharmProjects/TestPython/venv/bin/python /home/zhenglf/PycharmProjects/TestPython/Animal.py
horse' age: 10
horse' weight: 100
Hello: <__main__.Animal object at 0x7f3ed74cc908>
Hello: <__main__.Animal object at 0x7f3ed74cc908>
Hello: <__main__.Animal object at 0x7f3ed74cc908>
Hello: <class '__main__.Animal'>

Process finished with exit code 0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值