Must all Python instance variables be declared in def __init__?

后端 未结 4 2119
挽巷
挽巷 2021-01-02 05:36

Or can they be declared otherwise?

The code below does not work:

class BinaryNode():
    self.parent = None
    self.left_child = None
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 05:54

    Also, you can have class level variables, but I call them class constants.

    class Connection(object):
        """helps you connect to the server at work"""
        YOUR_IP = '10.0.9.99'
    
        def __init__(self, username, password):
            self.ip = Connection.YOUR_IP
            self.un = username
            self.pw = password
    
        #...and so on
    

提交回复
热议问题