JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

失业程序员复习python笔记——类

wys521 2025-04-27 17:03:58 精选教程 2 ℃ 0 评论

是一群相似事物的集合。Python中定义类的代码如下:

class Book():
def __init__(self,title,author):
self.title = title
self.author = author

def getTitle(self):
return "<<"+self.title+">>"

def getAuthor(self):
return " "+self.author

book = Book('python review note','regina')


其中代码第一行class Book() 就是定义了一个Book类。

对象是集合中的一个事物。对应代码里book = Book('python review note','regina')

表明Book集合中的一本具体的书。

属性是对象中某个特征,比如,title、author

函数是对象的某个行为,比如 getTitle、getAuthor


还有init函数表示构造函数,就是一个对象生成是就会被调用的函数。而getTitle和getAuthor是类的普通函数。


如果一个属性以 __ (注意,此处有两个 _) 开头,我们就默认这个属性是私有属性。私有属性,是指不希望在类的函数之外的地方被访问和修改的属性。


如果我在刚才那个类的基础上添加一个私有属性:

class Book():
def __init__(self,title,author,__content):
self.title = title
self.author = author
self.__content = __content


book = Book('python review note','regina','...python review')

print(book.__content)


如果你执行这段代码就会报AttributeError: 'Book' object has no attribute '__content'错误


那么怎么在类中定义一个常量呢?

class Book():
WELCOME_STR = 'This book is for python note'
def __init__(self,title,author,__content):
self.title = title
self.author = author
self.__content = __content


print(book.WELCOME_STR)


例如这段代码中的 WELCOME_STR。一种很常规的做法,是用全大写来表示常量


还有两个特殊的函数,一个是类函数,一个是静态函数。

比如上文代码中,我们使用 createJavaBook类函数,来创造新的书籍对象。类函数需要装饰器 @classmethod 来声明。


@classmethod
def createJavaBook(cls):
return cls('java review note','regina','nothing')


print(book.createJavaBook().title)


静态函数可以用来做一些简单独立的任务,既方便测试,也能优化代码结构。静态函数还可以通过在函数前一行加上 @staticmethod 来表示,代码中也有相应的示例。


@staticmethod
def get_welcome():
return Book.WELCOME_STR


print(Book.get_welcome())

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表