python学习-62 类属性的增 删 该 查

                                                                             类属性

 

 

1.类属性

类属性又称为静态变量,或者是静态数据。这些数据是与它们所属的类对象绑定的,不依赖于任何类实例。 

 

2.增 删 改 查

class zoo:
    country = 'china'
    def __init__(self,name,address,kind):
        self.name = name
        self.address = address
        self.kind = kind
    def monkey(self):
        print('this is monkey (%s)' %self.address)
    def tiger(self):
        print('this is tiger (%s)' %self.kind)
    def end(self):
        print('welcome to %s' %self.name)
dwy = zoo('chinese\'s zoo','beijing','others')

zoo.monkey(dwy)
zoo.tiger(dwy)
zoo.end(dwy)

# 对类的数据属性增 删 改 查

print(zoo.country)                  #  查看信息

zoo.country = 'US'                # 修改信息
print(zoo.country)


zoo.snake = 'this is snake'          # 增加
print(dwy.snake)


del zoo.country                 # 删除
del zoo.snake

print(zoo.__dict__)

 

运行结果:

this is monkey (beijing)
this is tiger (others)
welcome to chinese's zoo
china
US
this is snake
{'__module__': '__main__', '__init__': <function zoo.__init__ at 0x7fb30efb8d90>, 'monkey': <function zoo.monkey at 0x7fb30efb8f28>, 'tiger': <function zoo.tiger at 0x7fb30efc9048>, 'end': <function zoo.end at 0x7fb30efc9378>, '__dict__': <attribute '__dict__' of 'zoo' objects>, '__weakref__': <attribute '__weakref__' of 'zoo' objects>, '__doc__': None}

Process finished with exit code 0

 

3.

class zoo:
    country = 'china'
    def __init__(self,name,address,kind):
        self.name = name
        self.address = address
        self.kind = kind
    def monkey(self):
        print('this is monkey (%s)' %self.address)
    def tiger(self):
        print('this is tiger (%s)' %self.kind)
    def end(self):
        print('welcome to %s' %self.name)
dwy = zoo('chinese\'s zoo','beijing','others')

# 调用
zoo.monkey(dwy)
zoo.tiger(dwy)
zoo.end(dwy)


# 类的函数属性的增加

def eat(self,food):    
    print('%s 正在吃%s'%(self.name,food))
zoo.eat = eat
print(zoo.__dict__)                   # 以列表的方式 查看是否添加进去了

dwy.eat('')

 

运行结果:

this is monkey (beijing)
this is tiger (others)
welcome to chinese's zoo
{'__module__': '__main__', 'country': 'china', '__init__': <function zoo.__init__ at 0x7f90cdc3ed90>, 'monkey': <function zoo.monkey at 0x7f90cdc3ef28>, 'tiger': <function zoo.tiger at 0x7f90cdc4f048>, 'end': <function zoo.end at 0x7f90cdc4f378>, '__dict__': <attribute '__dict__' of 'zoo' objects>, '__weakref__': <attribute '__weakref__' of 'zoo' objects>, '__doc__': None, 'eat': <function eat at 0x7f90cdd49268>}
chinese's zoo 正在吃草

Process finished with exit code 0

 

转载于:https://www.cnblogs.com/liujinjing521/p/11457902.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值