Python类简述

类的定义用class

# Dog(object) 默认继承object,可以不写
class Dog():
    # 方法
    def work(self):
        pass

类属性及修改

# 修改类属性只能通过类对象,修改实例对象的值就相当于创建了一个实例对象的属性
class Dog():
    tooth = 10
# white和black为创建的实例对象
white = Dog()
black = Dog()
#
# print(Dog.tooth)
# print(white.tooth)
# print(black.tooth)
#
# Dog.tooth = 20
# print(Dog.tooth)
# print(white.tooth)
# print(black.tooth)

# white.tooth = 20
# print(Dog.tooth)
# print(white.tooth)
# print(black.tooth)

类方法

# 通过类方法访问私有类属性
class Dog():
    # 私有属性
    __tooth = 10

    @classmethod
    def get_tooth(cls):
        return cls.__tooth


black = Dog()
print(black.get_tooth())

静态方法可直接调用

class Dog():
    def work(self):
        print('work')

    @staticmethod
    def print_message():
        print('this is a staticmethod')


black = Dog()
black.print_message()
Dog.print_message()
black.work()
# Dog.work()

posted @ 2021-03-09 10:22  code-G  阅读(57)  评论(0)    收藏  举报