使用带有python错误的对象
嘿,伙计们,我是python开发的新手。我编写的代码使用带有python错误的对象,python,Python,嘿,伙计们,我是python开发的新手。我编写的代码 class Employee: def __init__(self, num, num1): self.num = num self.num1 = num1 def displayCount(self,x,y): d = x.self.num p = y.self.num1 c = d + p print c 当我调用如下函数时 emp1 =
class Employee:
def __init__(self, num, num1):
self.num = num
self.num1 = num1
def displayCount(self,x,y):
d = x.self.num
p = y.self.num1
c = d + p
print c
当我调用如下函数时
emp1 = Employee(3, 2000)
emp1.displayCount(3, 2)
它给了我类似于AttributeError的错误:“int”对象没有属性“self”
。我知道错误发生在x.self.num
。为什么用python可以做到这一点
希望你们能帮助我。谢谢。我想用你的
x.self.num
你正在尝试更新self.num
。如果没有,请在问题中指定错误
要解决上述问题,您可以使用self.num=x
重新分配:
class Employee:
def __init__(self, num, num1):
self.num = num
self.num1 = num1
def displayCount(self,x,y):
self.num = x
self.num1 = y
c = self.num+self.num1
print c
其运行方式如下:
>>> emp1 = Employee(3, 2000)
>>> emp1.displayCount(3,2)
5
>>>
如果该类的属性是另一个类的实例,它可能如下所示
class Location:
def __init__(self):
self.x = 0
self.y = 0
class Person:
def __init__(self):
self.loc = Location()
def set_coordinates(self, x_pos, y_pos):
self.loc.x = x_pos
self.loc.y = y_pos
p = Person()
p.set_coordinates(23, 42)
print(p.loc.x)
set_坐标
访问self.loc
。这是Location
的一个实例,因此我们可以在层次结构中进一步访问self.loc.x
在评论中进行了大量讨论之后,我将展示一些真正糟糕的代码,这些代码显示了像variable.self.anothervar
这样的东西是如何可能的
class Foo:
pass
class Bar:
def __init__(this):
this.self = Foo()
this.self.value = 23
class Baz:
def print_value(this, x):
print(x.self.value)
baz = Baz()
baz.print_value(Bar())
如您所见,
self
没有什么特别之处 你到底想用x.self.num
实现什么?@ZenOfPython我看到过一个类似于使用x.self.num的代码。它可以用python实现吗???。如果可以这样实现,请发布一个答案,说明代码在哪里?为什么要使用x.self.num
?是否要更新self.num
?您的问题不清楚,因为您对displayCount
的定义很模糊。你传递给Employee
类型的x
和y
是displayCount
还是他们应该是其他类型的人?@AlexReynolds我只是想知道如何添加self.onevarible.anothervaribale不..我知道如何做..但我的问题是我们可以添加第三个像x.self.num一样的变量吗???@user3805325什么你认为x.self
和self.x
是什么意思?假设它像self.name=“somename”。。我想像self.name.x=“somename”。。这可以在python中完成吗?是的,可以。但我不明白你真正想做什么。您还不了解面向对象编程,尝试做一些。。。奇怪。@Matthias请发布一个示例说明如何操作。这会很有帮助。我只想知道在哪种情况下,我们要添加self.x.anothervariable之类的变量。。