Python demo之 classdemo

本文介绍Python面向对象编程的基础概念及实现方法,通过实例演示了如何定义类与对象、使用继承特性,并展示了静态变量的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python和其他面向对象语言一样没有多少区别。过程就是这样:定义类,定义函数,创建对象,调用方法完成功能。继承就是类名后面加上() 然后加入父类的名称就OK

相对而言,要注意的就是self其实相当于java中的this,定义函数时,无参数的时候要加上这个self。具体看这个demo:class Person:

 

class Person:
    count = 0
    def __init__(self,name):
        self.name =name
        Person.count+=1
    def say(self):
        print("this is ", self.name)
        Person.count-=1
    def showCount(self):
        if(Person.count ==1):
            print("this is just  a start")
        if(Person.count ==0):
            print("this is just  an end")

class Man(Person):
    def __init__(self,name,age):
         Person.__init__(self,name)
         self.age = age
    def say(self):
         Person.say(self)
         print("this is from person", self.name)
    def showCount(self):
        if(Person.count ==2):
            print("this is just  a start from  Man")
        if(Person.count ==0):
            print("this is just  an end from  Man")

p = Person("shuofeng")
p.showCount()
p.say()
p.showCount()

man = Man("lxy",26)
man.showCount()
man.say()
man.showCount()
 

执行结果当然比较简单  就是打印 

 

this is just  a start

this is  shuofeng

this is just  an end

this is  lxy

this is from person lxy

this is just  an end from  Man

 

说明:这里的count就像是static 声明的一个静态变量一样。

 

 

PS:if  else  while等控制流和java区别不大,continue,break照常使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值