Python学习(Day11)——类和对象1

类和对象的创建及使用:


创建类

class Student:
    name='陌言'
    age=20
    place='Putian'
    #构造方法
    def __init__(self):
        pass
    #构造方法如果写了两个会以第二个为准,相当于第一个没写(似乎);
#    def __init__(self,name,age,place):
#        self.name=name
#        self.age=age
#        self.place=place


    #实例方法
    def name_change(self,name):    #方法名字尽量不要和类里面变量名字相同,不然调用变量的时候回变成调用类方法,输出了地址类型之类的(似乎)
        self.name=name

    def age_change(self,age):
        self.age=age

    def place_change(self,place):
        self.place=place

    def inf(self):
        print(f'Name:{self.name};  Age:{self.age};  Place:{self.place}')

    #静态方法
    @staticmethod
    def method():
        print('静态方法!')

    #类方法
    @classmethod
    def cm(cls):
        print('类方法')

注意点:

#构造方法如果写了两个会以第二个为准,相当于第一个没写(似乎);
#方法名字尽量不要和类里面变量名字相同,不然调用变量的时候回变成调用类方法,输出了地址类型之类的(似乎)


两种调用方法的方式:
1 对象名.方法名
2 类名.方法名(对象)

stu=Student()
print('Student1:',end='\t')
stu.inf()
stu2=Student()
stu2.age_change(18)           #修改数据
stu2.place_change('Dream')
print('Student2:',end='\t')
stu2.inf()

#第二种输出方式
Student.inf(stu)
Student.inf(stu2)

#可以通过 对象.变量名 直接调用类里面的属性
print('直接调用Place:',stu.place)
print('类默认Place:',Student.place)
Student.place='somewhere'     #仅修改了默认值,对于已修改的非默认值不进行改变
stu.inf()
stu2.inf()
stu3=Student()
stu3.name_change('someone')
stu3.inf()

结果:

Student1: Name:陌言; Age:20; Place:Putian
Student2: Name:陌言; Age:18; Place:Dream
Name:陌言; Age:20; Place:Putian
Name:陌言; Age:18; Place:Dream
直接调用Place: Putian
类默认Place: Putian
Name:陌言; Age:20; Place:somewhere
Name:陌言; Age:18; Place:Dream
Name:someone; Age:20; Place:somewhere

‘’
类方法和静态方法的使用

#类方法的使用,使用类名直接访问
Student.cm()
#静态方法,使用类名直接访问
Student.method()

类方法
静态方法!




动态绑定

#动态绑定属性
stu.game='Genshin'
print(stu.name,stu.age,stu.game)     #game属性仅存在于stu中
#print(stu2.name,stu2.age,stu2.game)    报错#AttributeError: 'Student' object has no attribute 'game'

#动态绑定方法
def show():
    print('这是函数!不是实例方法。')
stu.show=show()
stu.show
#stu2.show    #报错,AttributeError: 'Student' object has no attribute 'show'

结果:

陌言 20 Genshin
这是函数!不是实例方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值