Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python OOP默认构造函数创建_Python_Oop_Default Constructor - Fatal编程技术网

Python OOP默认构造函数创建

Python OOP默认构造函数创建,python,oop,default-constructor,Python,Oop,Default Constructor,我正在用Python创建一个类。我想从一开始就将变量设置为零,但我认为使用“username=none、password=none、url=none”效率低下。我有没有办法创建一个新的def\uuu init\uuuu(self):方法,该方法不接受任何参数并将所有属性设置为无?这是它当前的外观,感谢您的帮助!: Class Broken(): #pulls from function which is what username = none password =

我正在用Python创建一个类。我想从一开始就将变量设置为零,但我认为使用“username=none、password=none、url=none”效率低下。我有没有办法创建一个新的
def\uuu init\uuuu(self):
方法,该方法不接受任何参数并将所有属性设置为无?这是它当前的外观,感谢您的帮助!:

  Class Broken():
    #pulls from function which is what
    username = none
    password = none
    url = none
    job_url = none
    headers = none
相反,我想

def __init__(self):?????

您可以使用回退
\uuuu getattr\uuuu
方法来实现这一点。如果属性名称在列表中,则返回
None
。在下面的示例中,尝试获取a、b或c的值将返回
None
,除非已设置这些值

class Foo:
    def __init__(self):
        pass

    def __getattr__(self,attrname):
       if attrname in {'a','b','c'}:
           return None
       else:
           raise AttributeError(attrname)


f = Foo()
f.a = 23

print(f.a,f.b)
印刷品:

23 None
尝试访问另一个未设置的属性会引发
AttributeError
(我承认异常消息有点简练)

不会更简单。\u dict\u.get('username')?