python 基础拾遗(一) 类

2017-11-22  本文已影响0人  上海第一撸码少年

首先要说的是 python2是经典类,需要显式继承 object 才能成为一个新式类. pyhton3不需要这样.经典类和新式类还有其他区别,这里主要讲新式类.

1.最基础的属性,方法,变量,几个特殊属性

class ClassOne():
    '''
    类的文档说明
    '''
    # 类的属性
    this_property_one = 'this_property_one'
    this_property_two = 'this_property_two'

    # 类的变量
    def __init__(self, arg_one, arg_two):
        self.arg_one = arg_one
        self.arg_two = arg_two

    # 类的方法
    def this_method(self):
        return ('this_method')


my_class = ClassOne('my_arg_one', 'my_arg_two')

print my_class.this_property_one  # this_property_one
print my_class.arg_one  # my_arg_one
print my_class.this_method()  # this_method

print my_class.__dict__  # {'arg_two': 'my_arg_two', 'arg_one': 'my_arg_one'}  打印的是类的变量组成的字典
print my_class.__doc__  # 类的文档说明  打印的是类的文档
print my_class.__class__  # __main__.ClassOne  打印的是类对象的类型
print my_class.__class__.__name__  # ClassOne  打印的是类的名字
print my_class.__module__  # __main__  打印是的类所属的模块


2.类的类方法,静态方法,

class ClassTwo():
    name = 'shen'

    # 请注意,类方法可以访问到类的属性,不能访问到类的变量,静态方法都访问不到
    def __init__(self, color):
        self.color = color

    @classmethod
    def class_method(cls, arg):
        print cls.__name__
        print arg
        print 'this is name--{}'.format(cls.name)

    @staticmethod
    def static_method(arg):
        print arg


print ClassTwo.class_method('classmethod')
# ClassTwo
# classmethod
# this is name--shen
print ClassTwo.static_method('staticmethod')
# staticmethod
print '-' * 40


# 类方法的使用场景,可以参考 django 的https://docs.djangoproject.com/en/1.9/ref/models/instances/
class Book(object):
    def __init__(self, title):
        self.title = title

    @classmethod
    def create(cls, title):
        book = cls(title=title)
        return book

book1 = Book("python")
book2 = Book.create("some thing new")
print(book1.title) #python
print(book2.title) #some thing new
上一篇下一篇

猜你喜欢

热点阅读