应用场景
1.希望在对象保存一些值,而调用方法需要用一些值----普通方法。
2.不需要任何对象中的值----静态方法。
# -*-coding:utf-8 -*-
__author__ = 'xiaojiaxin'
__file_name__ = '面向对象实例练习'
class Foo():
#静态变量,属于类,在内存中只保存一份
country="中国"
def __init__(self,n):
#普通字段
self.name=n
#普通方法
def show(self):
print(self.name)
obj1=Foo("wang")
obj1.show()
# wang
print(Foo.country) #静态字段可以通过访问类直接访问,它就存在类中
# 中国
# print(Foo.name) #报错,普通字段不能通过类直接访问
# AttributeError: type object 'Foo' has no attribute 'name'
print(obj1.country) #静态字段还可以通过对象直接访问
# 中国
class fun():
def bar(self):
print("123")
@staticmethod #加装饰器变成静态方法
def staticmd():
print("ok")
@classmethod #类方法
def classmd(cls):
print(cls)
print("ok2")
fun.bar("obj2") #与下面两行等价
123
obj2=fun()
obj2.bar()
123
fun.staticmd() #静态方法可以用类直接调用
ok
fun.classmd()
<class '__main__.fun'>
ok2
转载于:https://blog.51cto.com/10777193/2102938