๐๐๐ ๐๐๐๐บ๐๐๐๐๐
[Python] What is "self" in Python? ๋ณธ๋ฌธ
In Python, "self" refers to the specific instance that is calling the method.
So, "self" is used to assign or update attributes for the specific instance.
# Defining a Class using "self"
class greatatcoding:
def __init__(self, name, age):
self.name = name # "self.name" is an instance attribute; "name" is a local parameter
self.age = age
def hello(self):
print(f"Hello, I'm {self.name} and I'm greatatcoding")
def bye(self):
# "self" being used to call other methods within the same class
self.hello()
print("and good bye~")
# Creating an instance
## so in this case, "self" refers to the instance "sarah"
sarah = greatatcoding("Sarah", 25)
# Calling a Method
sarah.hello() # Output: Hello, I'm Sarah and I'm greatatcoding
Let's look at another example!
This is a snippet of code from the text2video-zero model.
class TextToVideoPipeline(StableDiffusionPipeline):
def __init__(
self,
vae: AutoencoderKL,
text_encoder: CLIPTextModel,
tokenizer: CLIPTokenizer,
unet: UNet2DConditionModel,
scheduler: KarrasDiffusionSchedulers,
safety_checker: StableDiffusionSafetyChecker,
feature_extractor: CLIPFeatureExtractor,
requires_safety_checker: bool = True,
):
super().__init__(vae, text_encoder, tokenizer, unet, scheduler,
safety_checker, feature_extractor, requires_safety_checker)
When an instance of the class TextToVideoPipeline is created, the __init__ method (a.k.a. the constructor) is called. This method helps initialize the instance's specific attributes.
super().__init__() calls the constructor of the parent class which is the StableDiffusionPipeline and passes the required arguments.