python self method

本文深入探讨了Python中self关键字的作用及使用场景,解释了它如何帮助访问类的属性和方法,以及为什么Python选择self而非其他语法。通过实例展示了self在构造函数和类方法中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

'''
The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes. In Python, we have methods that make the instance to be passed automatically, but not received automatically.


'''
print('******Example*****')

class food():


    # init method or constructor
    def __init__(self, fruit, color):
        self.fruit = fruit


        self.color = color


    def show(self):
        print("fruit is", self.fruit)


        print("color is", self.color)

apple = food("apple", "red")
grapes = food("grapes", "green")

apple.show()
grapes.show()

print('******Python Class self Constructor*****')

'''
In the  example, self refers to the name variable of the entire Person class. Here, if we have a variable within a method, self will not work. That variable is simply existent only while that method is running and hence, is local to that method. For defining global fields or the variables of the complete class, we need to define them outside the class methods.

'''
class Person:
    # name made in constructor
    def __init__(self, John):
        self.name = John


    def get_person_name(self):
        return self.name

print('******Example*****')
class this_is_class:
    def show(in_place_of_self):

        print("It is not a keyword "
              "and you can use a different keyword")


object = this_is_class()
object.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值