python学习-私有方法/__del__方法/引用计数统计/__str__方法/继承/实例方法、类方法、静态方法

#私有方法,只有满足某种条件的时候才会被调用
class Mseg():
    def __send_msg(self):
        print('正在发送短信')

    def send_msg1(self,money):
        if money>=1000:
            self.__send_msg()
        else:
            print('余额不足')
Mseg().send_msg1(10)

#__del__方法的使用:程序结束的时候最终调用
class Dog():
    def __del__(self):
        print('end....')
dog1=Dog()
dog2=dog1

del dog1
# del dog2
print('hh')

#统计引用计数
import sys
print(sys.getrefcount(dog1))
#__str__调用类后,自动最终返回一个结果
class SweetPotato():
    def __init__(self):
        self.cookedString='生的'
        self.cookiedLevel=0
        self.zl_list=[]

    def __str__(self):
        return '状态:{},作料:{}'.format(self.cookedString,self.zl_list)

    def cook(self,cook_time):
        self.cookiedLevel+=cook_time
        if self.cookiedLevel>0 and self.cookiedLevel<=3:
            self.cookedString='生的'
        elif self.cookiedLevel > 3 and self.cookiedLevel <= 5:
            self.cookedString = '半生不熟'
        elif self.cookiedLevel > 5 and self.cookiedLevel <= 8:
            self.cookedString = '熟的'
        return self.cookedString

    def add_zl(self,zl):
        self.zl_list.append(zl)

a=SweetPotato()
a.cook(4)
# print(a.cook(1))
a.add_zl('番茄酱')
a.add_zl('孜然')
a.add_zl('胡椒')
# print(a.zl_list)
print(a)

 

'''继承'''
class Dog():
    def __init__(self):
        self.name='hh'
        self.__age=10

    #私有方法不能被子类直接调用
    def __eat(self):
        print('')

    def drink(self):
        print('')

    #公有方法类的私有方法可以被子类调用
    def ead(self):
        self.__eat()

class BigDog(Dog):
    def bark(self):
        print('汪汪叫')

class BigCat(Dog):
    def speak(self):
        print('喵喵叫')

#多继承
class Xiaotq(BigDog,BigCat):
    def fly(self):
        print('')

    # 重定义父类方法
    def bark(self):
        print('一直叫')
        #再次调用父类方法
        #方法一:
        # BigDog().bark()
        #方法二:
        # super().bark()

Xiaotq().ead()
Xiaotq().bark()
Xiaotq().speak()

 

首先,这三种方法都定义在类中。(PS:实例对象的权限最大。)

实例方法

    定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法);

    调用:只能由实例对象调用。

类方法

    定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法);

    调用:实例对象和类对象都可以调用。

静态方法

    定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法;

    调用:实例对象和类对象都可以调用。

class Game():
    #类属性
    num=0

    #实例方法
    def __init__(self):
        #实例属性
        self.name='cherry'

    #类方法(操作类属性)
    @classmethod
    def add_num(cls):
        cls.num=100

    #静态方法(调用一些简单的,与类方法、实例方法不大关联的)
    @staticmethod
    def print_menu():
        print('hello')
        print('world')

game=Game()
# game.add_num()#通过这个类创造出来的对象,去调用这个方法
Game.add_num()#也可以通过类的名字调用这个类方法
print(game.num)

game.print_menu()
Game.print_menu()

 

posted on 2019-07-28 12:15  cherry_ning  阅读(187)  评论(0)    收藏  举报

导航