标签:return 情况 子类 TE erro 构造方法 .sh eth 特殊
类 ==> 实例化 ==> 实例对象
__init__ 构造函数
self.name = name # 属性, 成员变量
def sayhi() # 方法, 动态属性
def get_heart(self):
return self.__heart # 提供对外访问接口, 但是外部只能获取其值,不能改变其值.
属性
#!/usr/bin/python # -*- coding: utf-8 -*- class Role(object): nationality = "JP" def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value # 公有属性 self.money = money self.__heart = "Normal" # 私有属性, 对外不可见(相当于java的private) def shot(self): print("%s is shooting" % self.name) self.__heart = "Dead" print(self.__heart) # 私有属性可以内部访问 def get_heart(self): return self.__heart # 提供对外访问接口, 但是外部只能获取其值,不能改变其值. def got_shot(self): print("ah... i got shot...") def buy_gun(self, gun_name): print("just bought %s" % gun_name) self.weapon = gun_name # 这样如果买了什么新武器, 也会同步更新属性weapon的值 r1 = Role(‘Alex‘, ‘police‘, ‘AK47‘) # 生成一个角色 r2 = Role(‘Jack‘, ‘terrorist‘, ‘B22‘) # 生成一个角色 r1.shot() r2.buy_gun(‘AK47‘) print(r2.weapon) # 在buy_gun()方法中添加self.weapon = gun_name, 这样若购买了新的武器, 就能更新属性weapon的值 # print(r1.get_heart()) print(r1._Role__heart) # 外部强行访问一个私有属性 # 更改类的公有属性有两种方法 Role.nationality = "US" # 方法1. 所有对象的nationality值都会被更改. r1.natiocnality = "Thailand" # 方法2. 只有对象r1的nationality值会被更改. def shot2(self): # 在类中, 直接调用方法, 会自动把实例对象传入方法. 在类外面的方法, 需要自己把实例传入方法. print("my own shot method") r1.shot = shot2 r1.shot(r1) # 调用的其实是shot2()方法. 因方法shot2()不在类中, 所以需要自己把参数传入.
面向对象的特性
标签:return 情况 子类 TE erro 构造方法 .sh eth 特殊
原文地址:https://www.cnblogs.com/cheese320/p/9165466.html