python – 传递变量,创建实例,自我,类的机制和用法:需要解释
作者:互联网
我一整天都坐在这里,我已经有点累了所以请原谅我简短.
我是python的新手.
我只是将一个工作程序重写成一个类中的一堆函数,一切都搞砸了.我不知道是不是我,但我很惊讶我找不到关于如何在网上处理课程的初学者教程,所以我有几个问题.
首先,在类的__init__部分,我已经声明了一堆变量self.variable = something.
通过在该函数中使用self.variable,我应该能够在类的每个函数中访问/修改这些变量是否正确?换句话说,通过声明self.variable我已经做了这些变量,类的范围内的全局变量对吗?
如果没有,我该如何处理自我?
其次,如何正确地将参数传递给类?一些示例代码很酷.
第三,如何在类范围之外调用类的函数?一些示例代码很酷.
第四,如何在另一个类OTHERCLASS中创建类INITIALCLASS的实例,将变量从OTHERCLASS传递到INITIALCLASS?一些示例代码很酷.
我想通过INITIALCLASS中的参数调用OTHERCLASS中的函数.到目前为止我所做的是.
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 object
bar = "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
标签:python,class,call,parameter-passing,instance-variables 来源: https://codeday.me/bug/20190929/1834028.html