[英]python basic class question, where am i going wrong
I'm slowly trying to get my head around classes.我正在慢慢地尝试了解课程。 I have a few working examples which i kinda understand but can someone please explain to me why this doesn't work?我有一些我有点理解的工作示例,但有人可以向我解释为什么这不起作用吗?
class python:
def __init__(self,name):
self.name=name
def changename(self,newname):
self.name=newname
abc=python('python')
print abc.name
abc.changename = 'anaconda'
print abc.name
All I'm trying to do here is change the value of abc.name
at some point later in the code (it doesn't need to be name if that's a special word, but I did try name2, etc, same results...)我在这里要做的就是在代码稍后的某个时刻更改abc.name
的值(如果这是一个特殊词,则不需要是 name,但我确实尝试过 name2 等,结果相同.. .)
If I do print abc.changename
then I get the output anaconda but that's not really what i wanted.如果我确实print abc.changename
然后我得到输出 anaconda 但这并不是我真正想要的。
Any help would be much appreciated.任何帮助将非常感激。
Also...Is it possible to do something like that at a later point in the life cycle of the code?另外......是否有可能在代码生命周期的后期做类似的事情?
def newstuff(self, value1, value2):
self.newvalue1 = value1
self.newvalue2 = value2
So that I would have access to 2 new 'things' abc.newvalue1
and abc.newvalue2
.这样我就可以访问 2 个新的“东西” abc.newvalue1
和abc.newvalue2
。
Does that make sense??那有意义吗??
Sorry for the 'things;为“事情”感到抱歉; I'm still trying to grasp which is an attribute, object, method, item, etc...我仍在试图掌握哪个是属性、对象、方法、项目等......
abc.changename
is a method. abc.changename
是一种方法。 To use it, write it with the parenthesis and the value into them.要使用它,请将它与括号和值一起写入其中。 abc.changename('anaconda')
Hope it'll help you abc.changename('anaconda')
希望对你有帮助
You declared abc.changename
as a function.您将abc.changename
声明为函数。 Invoke it by using abc.changename("Sandman112")
使用abc.changename("Sandman112")
调用它
What you did is you assigned a string to the member variable abc.changename
instead of the class method you defined eariler.您所做的是将一个字符串分配给成员变量abc.changename
而不是您之前定义的类方法。
Try changing this line:尝试更改此行:
abc.changename = 'anaconda'
to this:对此:
abc.changename('anaconda')
You defined the method changename
to access your member name
.您定义了方法changename
来访问您的成员name
。 Then, in the first line you try to access the member directly without using the method.然后,在第一行中,您尝试不使用该方法直接访问该成员。
In the second case, yes it would work:在第二种情况下,是的,它会起作用:
def newstuff(self, value1, value2):
self.name1 = value1
self.name2 = value2
But you would have to add 1 member to your class, and should then access the method like this:但是您必须向类中添加 1 个成员,然后应该像这样访问该方法:
class python:
def __init__(self, value1, value2):
self.name1 = value1
self.name2 = value2
abc=python('python1', 'python2')
abc.newstuff('snake', 'anaconda')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.