python 基础拾遗(一) 类

首先要说的是 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,715评论 19 139
  • 本文为《爬着学Python》系列第十四篇文章。 中间因为工作原因隔了好久没有更新,现在稳定很多,会陆续开始更新。不...
    SyPy阅读 14,182评论 1 10
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,013评论 18 399
  • 一:java概述:1,JDK:Java Development Kit,java的开发和运行环境,java的开发工...
    ZaneInTheSun阅读 7,602评论 0 11
  • swift版本:Apple Swift version 2.1 (swiftlang-700.1.101.6 cl...
    阿影阅读 5,601评论 1 1