传递变量,创建实例,自我,类的机制和用法:需要说明
我只是将一个工作程序重写为一个类中的函数,然后一切都搞砸了。
首先 ,在__init__
课程的部分中,我用声明了一堆变量self.variable=something
。
通过使用self.variable
该函数,是否应该能够在类的每个函数中访问/修改这些变量?换句话说,通过声明self.variable
我已经做了这些变量,在类范围内的全局变量对吗?
如果没有,我该如何处理自我?
其次 ,如何正确将参数传递给类?
第三 ,如何在类范围之外调用类的函数?
第四 ,如何class INITIALCLASS
在另一个实例中创建的实例class
OTHERCLASS
,并将变量从传递OTHERCLASS
到INITIALCLASS
?
我想使用来自OTHERCLASS
的参数来调用函数INITIALCLASS
。到目前为止,我所做的是。
class OTHERCLASS():
def __init__(self,variable1,variable2,variable3):
self.variable1=variable1
self.variable2=variable2
self.variable3=variable3
def someotherfunction(self):
something=somecode(using self.variable3)
self.variable2.append(something)
print self.variable2
def somemorefunctions(self):
self.variable2.append(variable1)
class INITIALCLASS():
def __init__(self):
self.variable1=value1
self.variable2=[]
self.variable3=''
self.DoIt=OTHERCLASS(variable1,variable2,variable3)
def somefunction(self):
variable3=Somecode
#tried this
self.DoIt.someotherfunctions()
#and this
DoIt.someotherfunctions()
我显然不明白如何将变量传递给类或如何处理self
,何时使用变量以及何时不使用变量。我可能也不太了解如何正确创建类的实例。通常,我不了解类的机制,因此请帮助我并向我解释,就像我不知道(似乎我不知道)一样。或为我提供完整的视频或易读的教程。
我在网上找到的只是超级简单的示例,并没有太大帮助。或者只是非常简短的类和类方法实例等的定义。
如果您愿意,我可以将原始代码发送给您,但是它很长。
-
class Foo (object):
# ^class name #^ inherits from objectbar = "Bar" #Class attribute. def __init__(self): # #^ The first variable is the class instance in methods. # # This is called "self" by convention, but could be any name you want. #^ double underscore (dunder) methods are usually special. This one # gets called immediately after a new instance is created. self.variable = "Foo" #instance attribute. print self.variable, self.bar #<---self.bar references class attribute self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute print self.variable, self.bar def method(self, arg1, arg2): #This method has arguments. You would call it like this: instance.method(1, 2) print "in method (args):", arg1, arg2 print "in method (attributes):", self.variable, self.bar a = Foo() # this calls __init__ (indirectly), output: # Foo bar # Foo Bar is now Baz print a.variable # Foo a.variable = "bar" a.method(1, 2) # output: # in method (args): 1 2 # in method (attributes): bar Bar is now Baz Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is. class Bar(object): def __init__(self, arg): self.arg = arg self.Foo = Foo() b = Bar(a) b.arg.variable = "something" print a.variable # something print b.Foo.variable # Foo