标签:通过 静态方法 ssm assm pytho ini 定义 aaa elf
类的成员有:普通字段、普通方法、静态字段、静态方法、类方法
调用方法: self 对象调用obj.f1(), 无self 类调用Foo.f1()
一、.静态字段、普通字段
1、字段调用时,不需要括号
class Faa:
#静态字段
country = "China" #可以当成一个self.country 使用。
def __init__(self,name):
#普通字段
self.n = name
d = Faa("河南")
r1 = d.n
r2 = d.country #调用字段时不用加括号的。
print(r1,r2)
#河南 China
一、.静态方法、普通方法
1、 静态方法 @staticmethod
class Foo:
def __init__(self,name,age):
self.n = name
self.a = age
def f1(self):
ret = "name: %s age: %s"%(self.n,self.a)
return ret
@staticmethod
def f2(a,b,c):
d = "%s %s %s." % (a,b,c)
return d
#1. 在类中定义静态方法是要用装饰器@staticmethod
#2. 在调用时 通过类 而非对象,切记。
#3. 静态方法与普通方法的名字不能重复。
obj = Foo("Coob",18)
r1 = obj.f1()
r2 = Foo.f2("ww","xx","aa")
print(r1)
print(r2)
#name: Coob age: 18
#ww xx aa.
三、类方法
1、类方法,就是静态方法加个当前的类名。
2、@classmethod 类方法
3、定义方法时,最后一个参数会自动把当前的类名添加进去。
class Foo:
def __init__(self,name,age):
self.n = name
self.a = age
@classmethod
def f1(cls): # cls 自动把类名传入
print("xxx",cls)
#1.需要加装饰器 @classmethod
#2.定义时参数cls 必须要写 cls 即是 当前类名。
Foo.f1()
四、特性
1、通过对象调用函数时不用加括号的。
2、@property
class Foo:
def __init__(self,name,age):
self.n = name
self.a = age
@property
def f1(self):
return "aaa"
obj = Foo("I","ddd")
a = obj.f1
print(a)
#aaa
标签:通过 静态方法 ssm assm pytho ini 定义 aaa elf
原文地址:http://www.cnblogs.com/learn-python-M/p/6844572.html