python类的定义和使用

电脑杂谈  发布时间:2020-05-17 19:04:02  来源:网络整理

python 类_python 静态类_python 类 attribute

Python中的类声明使用关键字class提供可选的父类或基类. 如果没有合适的基类,则使用object作为基类.

定义格式:

class 类名(object):
    "类的说明文档"
    属性
    初始方法__init__
    其他方法

python 类 attribute_python 静态类_python 类

什么与其他面向对象的语言不同?

没有关于属性的公共或私人声明. 没有构造方法,初始方法只是实例化时将要执行的方法. 定义方法时,必须带self参数,类似于java中的参数.

简单的例子

python 类 attribute_python 静态类_python 类

class User(object):
    "This is user class."
    name = "tom"
    age = 0
    def __init__(self, age=22):
        self.age = age
    def showAge(self):
        print self.age
    def showClassName(self):
        print self.__class__.__name__
    def showClassDoc(self):
        print self.__class__.__doc__

实例化此类:

user = User()

python 静态类_python 类_python 类 attribute

在类中调用属性名称

print user.name

在类中调用showAge()方法

python 类_python 静态类_python 类 attribute

user.showAge()

获取类的名称,可以使用self .__类__.__ name__进行获取python 类,请参考上面示例中的showClassName方法

user.showClassName()

要获取类描述文档python 类,可以使用self .__ class __.__ doc__来获取它. 请参考以上示例中的showClassDoc方法. 使用此方法,您可以快速生成整个项目的类描述文档.


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-213401-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...