Python 面向对象3
2021-06-19 20:06
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 作者:Presley
# 邮箱:1209989516@qq.com
# 时间:2018-08-05
# OOP学习1class Role(object):
members = 0
ac = None
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.aaa = 1
Role.members += 1#每增加一个实例则members值加1
def shot(self):
print("shooting...")def got_shot(self):
print("ah...,I got shot...")def buy_gun(self,gun_name):
print("just bought {0}".format(gun_name))
self.gun_name = gun_name
print(self.aaa)
print(self.ac)#在没有实例化之前是不能调实例化中的属性的但是可以掉用类中的属性
print(Role.ac)#能打印
#print(Role.weapon)#报错,显示没有weapon,因为没有实例化
#Role的实例
#把一个抽象的类变成一个具体的对象的过程
r1 = Role("wohaoshuai1","police","AK47")#生成一个角色
#相当于Role(p1,"wohaoshuai","police","AK47")r2 = Role("wohaoshuai2","police","B22") #生成一个角色
print("r2",r2.ac,r2.weapon,Role.members)r3 = Role("wohaoshuai3","police","AK47")
#r1.buy_gun("AK47") #会自动转换成Role.buy_gun(r1,"AK47")
r1.ac = "China Brand"
r2.ac = "US Brand"Role.ac = "riben Brand"
Role.weapon = "riben wepon"print("r1:",r1.ac,r1.weapon,Role.members)
print("r2",r2.ac,r2.weapon,Role.members)
print("r3",r3.ac,r3.weapon,Role.members)‘‘‘总结:
1、ac是类的属性
2、weapon是实例属性
3、实例访问方法或属性的时候其实是访问其类的方法或属性,无论一个类中有多少个实例对象,当他们访问对象中的方法或属性的时候都是调用类的方法或属性
‘‘‘
下一篇:C++ 指向函数指针