实例方法、类方法与静态方法

实例方法:与具体实例相关,用于操作实例变量
类方法:与类相关,用于操作类变量,虽然实例可以直接调用,但是不建议通过实例调用
静态方法:与类和具体实例无关,相当于一个独立的函数

实例方法
class Person():
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height

def Person_self(self):
print("My name is %s,is %d,I\'m %d cm"%(self.name,self.age,self.height))


person = Person('tomcat',11,171)
person.Person_self()


类方法
class Person():
total = 1

@classmethod
def person_total(cls):
cls.total += 1
print(cls.total)

Person.person_total()

静态方法
class Person():
total = 1

@staticmethod
def print_hello():
print("hello,world")
print(total) #NameError: name 'total' is not defined

Person.print_hello()
posted @   故y  阅读(83)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-06-27 2021.6.27
点击右上角即可分享
微信分享提示