python 实战 类_Python实用章类,python,实战篇

目录

1、Python的类如何定义?

class Fruit:

# 类属性

price = 0 # 通过类名和对象名都可见

def __init__(self):

self.__color="Red" # 定义和设置私有属性

self.__city = 'beijing' # 定义和设置私有属性

def __outputColor(self): # 定义私有方法

print(self.__color)

def __outputCity(self): # 定义私有方法

print(self.__city)

def output(self): # 定义共有方法

self.__outputColor()

self.__outputCity()

@ staticmethod

def getPrice(): # 定义静态方法

return Fruit.price

@ staticmethod

def setPrice(p):

Fruit.price = p

python的类定义也离不开关键字class,属性(成员变量)有两种,一种是实例属性,一种是类属性。其中实例属性是在构造函数__init__()中定义的。

2、访问成员或调用方法

from Fruit import Fruit

if __name__ == '__main__':

apple = Fruit()

# 通过对象名访问公有方法

apple.output()

# 通过类名访问公邮方法

Fruit.output(apple)

# 通过对象名访问静态方法

apple.setPrice(23)

print(apple.price)

# 通过类名访问静态方法

print(Fruit.getPrice())

Fruit.setPrice(100)

print(Fruit.getPrice())

3、类的继承

class Animal:

def run(self):

print('Animal is running')

class Cat(Animal):

def run(self):

python中的继承是子类名之后的括号中写明父类名,与java不同,Java用关键字extends 标识。

4、python中的多态

class Animal:

def run(self):

print('Animal is running')

class Cat(Animal):

def run(self):

print('cat is running')

class Dog(Animal):

def run(self):

print('dod is running')

if __name__ == '__main__':

cat = Cat()

dog = Dog()

a = Animal()

cat.run()

dog.run()

a.run()

打印结果:

cat is running

dod is running

Animal is running

总结:子类会覆盖父类中的run方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值