Python- 面向对象的编程

静态属性、静态方法、类方法

class npc:
    count=1            # 静态属性
    
    @staticmethod        # 静态方法
    def describe1():
        print("npc是玩家非可控角色,通常由电脑按游戏逻辑执行")
        
     @classmethod
     def describe2( ):
         print( " 我是类方法 ")
         
    def __init__(self, name,attack):
        self.__name = name           #对象属性
        self.__attack = attack
        npc.count=npc.count+1           # 静态属性count用于计数

    def __str__(self):
        return "角色名:%s,攻击力:%d" % (self.__name,self.__attack)

    def attack(self):                #成员方法
        print("%s正在攻击...." % self.__name)


if __name__ == "__main__":
    n1 = npc("豌豆射手", 12)
    print(n1)
    n2 = npc("食人花", 100)
    print(n2)
    
    print(“一共创建了%d个对象” % npc.count)
    
    n1.attack()
    n2.describe1()  
    npc.describe1()
    npc.describe2()  

【对象属性】如此代码中的name、gj。
只有定义对象时才定义,又称成员属性。

【成员(对象)方法】如此代码中的attack(self)。
一定有self参数

【静态方法】如此代码中的describe1()。

@staticmethod
 def describe( ):
    print("npc是玩家非可控角色,通常由电脑按游戏逻辑执行")

① 用@staticmethod装饰器修饰,无参数。
②=“ 定义在类中的全局函数
③静态方法若有参数,不会将第一个参数看做调用对象。
④调用方式为:a.)类名.静态方法名 b.) 类的对象名.静态方法名(不建议)。

【类方法】如此代码中的describe2()。
①用@classmethod装饰器修饰,第一个参数是当前类。
②调用方式是“类名.类方法名”

【静态属性】如此代码中的count。
①定义在方法之外,地位=全局属性。
②不依赖于对象,在定义类时就已定义。
③任何地方(包括类内部)的访问方式都是 “类名.静态属性”。

slots

example:为类绑定变量和方法

class Student:
    pass


s1 = Student()
s1.name = "ZhangSan"
s1.age = 12           #为类动态绑定成员属性
print(s1.name,s1.age)

def printinfo(self):
    print("Student类的一个对象%s已创建"%(self.name))

#为类动态绑定方法
s1.printinfo=printinfo

s1.printinfo(s1)

【slots】
①用法:slots = (“属性1”,“属性2”…)
②功能:只允许对类绑定括号内的属性。(对类的方法的绑定没有限制)

example:

 class Student:
        __slots__=("name","age")

@property

attribute是python的属性,property是Java中的属性。

@
装饰器,功能:代替get、set方法

example:

class S:
    def __init__(self,atr):
        self.__atr=atr

    @property
    def atr(self):
        print("property输出装饰器被调用")
        return self.__atr
   """代替:def getatr(self):
            return self.__atr
   """

    @atr.setter
    def atr(self,NewAtr):
        print("property修改装饰器被调用")
        self.__atr = NewAtr
     """ 代替:def setatr(self):
               self.__atr=atr
     """


a=S("XiaoMing")
#print(a.__atr)
print(a.atr)

a.atr="DaMing"
print(a.atr)

猜你喜欢

转载自blog.csdn.net/versionkang/article/details/88189311