Py 定义类 基础

#1.定义类                                       类方法:类名,实例对象
                                               #类:类名
class Dog():
    tooth=10

    #定义类方法
    @classmethod
    def get_tooth(cls):
        return cls.tooth  #类方法获取这个类属性
    #对类属性进行修改
    @classmethod
    def set_tooth(cls,num):
        cls.tooth=num

#2.创建对象,调用类方法:能够通过实例对象和类去访问
wangcai=Dog()
xiaohei=Dog()
print(wangcai.tooth)


#3.访问类属性:类和实例对象 对象都可以访问
print(Dog.tooth)
print(wangcai.tooth)
print(xiaohei.tooth)


#1.类 类.类属性=值,修改类属性,必须通过类名去引用然后进行修改
Dog.tooth=20
print(Dog.tooth)
print(wangcai.tooth)
print(xiaohei.tooth)

#2.测试通过对象修改类属性,对象是修改不了类属性
wangcai.tooth=200          #会产生一个同名的实例属性,这种方式修改的是实例属性,不会影响到类属性
print(Dog.tooth)
print(wangcai.tooth)
print(xiaohei.tooth)

# 类里面
# self.属性名
# 类外面
# 对象名.属性名



#1.定义洗衣机类
"""
class 类名():
  代码
"""
class Washer():
    #创建实例方法:def 方法名(self,属性值1,.....):
    def wash(self): #o实例方法:通过实例对象调用的方法,self:对象自身的意思
        print('能洗衣服')
    def set_name(self,name):
        self.name=name     #实例属性:self.属性名=值
    def get_name(self):
        return self.name    #获得实例属性

#创建对象
#对象名=类名()
haier=Washer()
#使用wash功能--实例方法时--对象名.wash
haier.wash()#调用该方法时,就将该对象作为第一个参数传递给self
haier.set_name('海尔')
print(haier.get_name())
print(haier.name)#实例属性只能是对象才能访问
#print(Washer.name) #报错,类无法访问实例属性



#2.创建对象,调用类方法:能够通过实例对象和类去访问
wangcai=Dog()
print(wangcai.get_tooth())   #对象调用类方法
print(Dog.get_tooth())      #用类调用类方法

wangcai.set_tooth(20)        #对象调用类方法
#Dog.set_tooth(20)    #类调用类方法

print(wangcai.get_tooth())    #对象调用类方法
print(Dog.get_tooth())      #类调用类方法


#1.定义类,定义静态方法                     写相关的说明:
class Dog():
    @staticmethod
    def info_print():
        print("这是一个静态方法")

#2.创建对象
wangcai=Dog()

#3.
wangcai.info_print()
Dog.info_print()
  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值