码迷,mamicode.com
首页 > 编程语言 > 详细

python 面向对象整理 --------1.类和实例的属性

时间:2018-07-24 23:48:24      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:fun   div   attr   nbsp   cts   int   面向对象   ict   function   

1.类的属性:

# /usr/bin/env
# coding = utf-8
class Chinese:
  #类的属性在这
    country = ‘China‘

    def __init__(self, name):
      #实例的属性在这
        self.name = name

    def play_ball(self, ball):
        print(‘%s正在打%s‘ % (self.name, ball))


#查看属性
print(Chinese.country)

#修改属性
Chinese.country=‘Japan‘
print(Chinese.country)

p1=Chinese(‘alex‘)
print(p1.__dict__)
print(p1.country)

#增加属性
Chinese.dang=‘党‘

print(Chinese.dang)
print(p1.dang)

#删除属性
del Chinese.dang
del Chinese.country

print(Chinese.__dict__)
# print(Chinese.country)
结果:

China
Japan
{‘name‘: ‘alex‘}
Japan
党
党
{‘__module__‘: ‘__main__‘, ‘__init__‘: <function Chinese.__init__ at 0x0000028B584A66A8>, ‘play_ball‘: <function Chinese.play_ball at 0x0000028B584A6620>, 
‘__dict__‘: <attribute ‘__dict__‘ of ‘Chinese‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Chinese‘ objects>, ‘__doc__‘: None}
增加函数属性:

#定义一个函数
def eat_food(self,food):
    print(‘%s正在吃%s‘%(self.name,food))

#把这个函数给类
Chinese.eat=eat_food

print(Chinese.__dict__)
p1.eat(‘屎‘)

#test
def test(self):
    print(‘test‘)

Chinese.play_ball=test
p1.play_ball()

 

结果:

alex正在吃屎
test

 

2.实例的属性:

 

#/usr/bin/env
#coding = utf-8
class Chinese:
    country=‘China‘
    def __init__(self,name):
        self.name=name

    def play_ball(self,ball):
        print(‘%s正在打%s‘%(self.name,ball))

p1=Chinese(‘alex‘)
print(p1.__dict__)


#增加
p1.age=18
print(p1.__dict__)
print(p1.age)

#不要修改底层的属性字典
# p1.__dict__[‘sex‘]=‘male‘
# print(p1.__dict__)
# print(p1.sex)

#修改
p1.age=19
print(p1.__dict__)
print(p1.age)

 

 

结果:

{‘name‘: ‘alex‘}
{‘name‘: ‘alex‘, ‘age‘: 18}
18
{‘name‘: ‘alex‘, ‘age‘: 19}
19

 

python 面向对象整理 --------1.类和实例的属性

标签:fun   div   attr   nbsp   cts   int   面向对象   ict   function   

原文地址:https://www.cnblogs.com/solarzc/p/9363195.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!