028、方法与属性
本文最后更新于 68 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

方法与属性

自定义类型中通常要定义一些方法和属性。

手动添加属性

属性可以手动添加:

class Leaf(object):
    """A leaf falling in the woods."""
    pass
leaf = Leaf()
leaf.color = "green"
leaf.color
'green'

这样添加的新属性只对当前定义的对象有效,不能在新对象上使用:

leaf2 = Leaf()
leaf2.color
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

Input In [6], in ()
----> 1 leaf2.color

AttributeError: 'Leaf' object has no attribute 'color'

添加普通方法

添加普通方法需要用def关键字定义。向Leaf类中添加一个新方法,表示树叶下落:

class Leaf(object):
    """A leaf falling in the woods."""
    def fall(self, season="autumn"):
        """A leaf falls."""
        print(f"A leaf falls in {season}!")
leaf = Leaf()

查看帮助:

leaf.fall?

调用该方法时,self参数不用传入,会自动转化为对象leaf,因此只需要传入season参数。不带参数时,season用默认值:

leaf.fall()
A leaf falls in autumn!

构造方法.__init__()

通常通过构造方法.__init__(),在构造对象的时候添加属性。该方法在构造对象时会自动调用:

class Leaf(object):
    """A leaf falling in the woods."""
    def __init__(self, color="green"):
        self.color = color
leaf2 = Leaf("orange")
leaf2.color
'orange'

由于在.__init__()函数中指定了默认参数,在构造时,也可以不传入color参数时,.color属性为默认值“green”:

leaf = Leaf()
leaf.color
'green'
谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇