Python34-04-oop

本文介绍Python中的面向对象编程概念,包括类的定义、实例化、继承等核心特性,并通过具体示例展示了如何利用这些特性进行编程。

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

##添加多行注释:Alt + 3

##取消多行注释:Alt + 4

##IDLE菜单栏的Options -> Configure IDLE… -> Keys选项卡

 

#类

##class Bird(object):

##    have_feather = True

##    way_of_reproduction  = 'egg'

    

##summer = Bird()

##print (summer.way_of_reproduction)

##括号中的object,当括号中为object时,说明这个类没有父类

 

#动作

class Bird(object):

    have_feather = True

    way_of_reproduction = 'egg'

    def move(self, dx, dy):

        position = [0,0]

        position[0] = position[0] + dx

        position[1] = position[1] + dy

        return position

 

summer = Bird()

print ('after move:',summer.move(5,8))

 

#子类--继承(inheritance)

class Chicken(Bird):

    way_of_move = 'walk'

    possible_in_KFC = True

 

class Oriole(Bird):

    way_of_move = 'fly'

    possible_in_KFC = False

 

summer = Chicken()

print (summer.have_feather)

print (summer.move(5,8))

#在类定义时,括号里为了Bird。这说明,Chicken是属于鸟类(Bird)的一个子类,即Chicken继承自Bird。自然而然,Bird就是Chicken的父类。Chicken将享有Bird的所有属性

 

#调用类的其它信息---通过self,调用类属性

##class Human(object):

##    laugh = 'hahahaha'

##    def show_laugh(self):

##        print (self.laugh)

##    def laugh_100th(self):

##        for i in range(100):

##            self.show_laugh()

##

##li_lei = Human()          

##li_lei.laugh_100th()

 

#__init__()方法--特殊方法(special method)创建对象时,Python会自动调用这个方法。这个过程也叫初始化

class happyBird(Bird):

    def __init__(self,more_words):

        print ('We are happy birds.',more_words)

 

summer = happyBird('Happy,Happy!')

 

#对象的性质

class Human(object):

    def __init__(self, input_gender):

        self.gender = input_gender

    def printGender(self):

        print self.gender

 

li_lei = Human('male') # 这里,'male'作为参数传递给__init__()方法的input_gender变量。

print li_lei.gender

li_lei.printGender()

 

 

##动态类型(dynamic typing)

##Python的变量(variable)不需要声明,而在赋值时,变量可以重新赋值为任意值。这些都与动态类型的概念相关

##引用和对象分离,是动态类型的核心。引用可以随时指向一个新的对象

##a = 3

##a = 'at'

##第一个语句中,3是储存在内存中的一个整数对象。通过赋值,引用a指向对象3。

##第二个语句中,内存中建立对象‘at’,是一个字符串(string)。引用a指向了'at'。此时,

##    对象3不再有引用指向它。Python会自动将没有引用指向的对象销毁(destruct),释放相应内存

 

##从动态类型看函数的参数传递

def f(x):

    x = 100

    print (x)

 

a = 1

f(a)

print (a)

 

##如果参数是不可变(immutable)的对象,a和x引用之间相互独立,对参数x的操作不会影响引用a

##如果传递的是可变(mutable)的对象,那么改变函数参数,有可能改变原对象。

 

def f1(x):

    x[0] = 100

    print (x)

 

a1 = [1,2,3]

f1(a1)

print (a1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值