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

时间:2020-05-20 16:12:58

标签: python object attributes

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


t = test(1, 2)

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

让我们说,由于某种原因,我想创建一个类测试的实例,该实例仅具有第一个属性,而第二个则保留为null或其他任何值。是否有可能在不创建其他类的情况下这样做?如果可能的话,我想没有继承。

5 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

t1 = test(1, None)

t2 = test(None, 2)

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

答案 2 :(得分:0)

您可以使用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`

答案 3 :(得分:0)

您可以不使用任何一个吗?

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

答案 4 :(得分:0)

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

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.twoself.one成为None怎么办?

使用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)