给定 python 中的一个对象,我能否以某种方式将一个属性留空?

Given an object in python, can I somehow leave one attribute empty?

class test:
    def __init__(self, _one, _two):
        self.one = _one
        self.two = _two


t = test(1, 2)

print(t.one)
print(t.two)

比方说,出于某种原因,我想创建一个 class 测试实例,它只有第一个属性,而第二个属性为 null oder。有没有可能在不创建不同的 class 的情况下这样做?如果可能的话,我想不继承。

如果我理解正确你的目标,你可以使用默认参数:

class test:
    def __init__(self, _one = None, _two =None):
        self.one = _one
        self.two = _two


t = test(1, 2)

print(t.one) #1
print(t.two) #2

t = test(_one=1)

print(t.one) #1
print(t.two) #None

t = test(_two=2)

print(t.one) #None
print(t.two) #2

是的,您可以将 None 传递给构造函数。

t1 = test(1, None)

t2 = test(None, 2)

在对属性进行算术运算之前,请小心检查 None,因为这会引发 TypeError.

您可以使用 default 值,例如:

class test:
    def __init__(self, _one, _two=None):
        self.one = _one
        self.two = _two

test(_one=1) #should be fine, will assign None to `_two`

你可以使用 None 吗?

class test:
    def __init__(self, _one=None, _two=None):
        self.one = _one
        self.two = _two

是的,你可以做到。只是做:

class test:
def __init__(self, _one=None, _two=None):
    self.one = _one
    self.two = _two

现在您可以像这样创建对象:

t = test(1, 2)
t1 = test(3)
print(t.one, t.two)
print(t1.one, t1.two)

输出:

(1, 2) (3, None)

此方法的问题在于,当您执行 t1 = test(3) 时,self.one 将是 3,而 self.two 将是 None。但是如果你想要 self.two 被初始化并且 self.oneNone 怎么办?

解决此问题使用t1 = test(_two=3)。现在当你这样做时

t = test(1, 2)
t1 = test(_two=3)
print(t.one, t.two)
print(t1.one, t1.two)

输出将是 (1, 2) (None, 3)