类属性和实例属性

xiaoxiao2021-02-28  60

(1)类对象和实例对象的区别     类对象: 是类名     实例对象:是类实例化的对象 (2)类属性和实例属性的区别     类属性:1、类对象.属性 = 值         2、定义在类内部,方法外部     实例属性:1、在类中,self.属性    self当前实例对象           2、在类外,实例对象.属性 (3)类方法和实例方法和静态方法的区别     实例方法:     语法:         必须有一个参数,这个参数表示当前实例对象,一般是self     调用:         只能通过实例对象调用     类方法:     语法:         必须有一个参数,这个参数表示当前类对象,一般是cls。在方法的头部加注解(装饰器)@classmethod     调用:         实例对象可以调用         类对象可以调用          静态方法:     语法:普通函数的格式,不需要强制要求传递参数。在方法的头部加注解(装饰器)@staticmethod           一般用于与实例对象、类对象无关的内容     调用:         实例对象可以调用

        类对象可以调用

class Flower: #类属性 nums = 10 #实例方法 def __init__(self,breed,color): #实例属性 self.breed = breed self.color = color self.nums_operate() #实例方法 def info(self): print('品种:%s,颜色:%s'%(self.breed,self.color)) #类方法 @classmethod def nums_operate(cls): cls.nums -= 1 #静态方法 @staticmethod def residue(): if Flower.nums <= 0: print('今日鲜花已卖完!!') else: print('今日鲜花还剩:%s'%(Flower.nums)) f = Flower('百合','白色') print(f.nums) print(Flower.nums) f.nums_operate() Flower.nums_operate() f.residue() Flower.residue() f.info() Flower.info(f)

转载请注明原文地址: https://www.6miu.com/read-59665.html

最新回复(0)