计算圆的周长和面积
import math
class Circle():
def __init__(self,r):
self.r=r
def zhouchang(self):
return 2*math.pi*self.r
def mianji(self):
return math.pi*pow(self.r,2) #pow必须传两个参数
obj=Circle(5)
print(obj.zhouchang())
print(obj.mianji())
class Game_role():
def __init__(self,name,ad,hp):
self.name=name
self.ad=ad
self.hp=hp
def attack(self,obj):
obj.hp -=self.ad
strvar="{}攻击{},{}掉了{}血,还剩{}血"
print(strvar.format(self.name,obj.name,obj.name,self.ad,obj.hp))
P1=Game_role("盖伦",10,100)
P2=Game_role("剑豪",20,80)
P1.attack(P2)
#创建AB两个类,A类中有属性abc=5把A类的对象存储在B类对象的成员属性pty中,用B类对象调用出abc这个值
class A():
abc=5
class B():
def __init__(self,obj):
self.pty=obj
a=A()
b=B(a)
print(a.abc)
print(b.pty.abc)
class Person():
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def print_str(self):
strvar="""
{0},{1}岁,{2},上山去砍柴
{0},{1}岁,{2},开车去东北
{0},{1}岁,{2},最爱大保健
"""
res=strvar.format(self.name,self.age,self.sex)
print(res)
p1 = Person("小明",10,"男")
p1.print_str()
p2 = Person("刘伟",78,"男")
p2.print_str()