Python int 关键字 特征

本文详细介绍了Python中int类型的使用方法及特性,包括如何将不同形式的数据转换为整数、位操作方法、以及如何处理不同进制的数字字符串。同时,还介绍了int类型的一些特殊方法如bit_length等。

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

class int(object):
    """
    int(x=0) -> integer
  • x = int(), x 默认为0
  • 也可以设置为其他值,比如 x = int(5),结果是5
    int(x, base=10) -> integer
  • 转换字符串为数值,默认是按照10进制转换,返回结果是10进制
  • int(‘11’,10), 结果是10
  • int('11',2), 结果是3
  • int('11', 8), 结果是9
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is a number, return x.__int__().  For floating point
    numbers, this truncates towards zero.
  转换数字或者字符串为一个整数, 或者当无参数时返回0。如果x是一个数,返回x. 
对于浮点数,会向0方向取整。int(11.1), 结果是11. int(11.8), 结果是11.
    
    If x is not a number or if base is given, then x must be a string,
    bytes, or bytearray instance representing an integer literal in the
    given base.  The literal can be preceded by '+' or '-' and be surrounded
    by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
    Base 0 means to interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    4
    """
    def bit_length(self): # real signature unknown; restored from __doc__
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ Returns self, the complex conjugate of any int. """
        pass

    @classmethod # known case
    def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        int.from_bytes(bytes, byteorder, *, signed=False) -> int
        
        Return the integer represented by the given array of bytes.
        
        The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument indicates whether two's complement is
        used to represent the integer.
        """
        pass

    def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        int.to_bytes(length, byteorder, *, signed=False) -> bytes
        
        Return an array of bytes representing an integer.
        
        The integer is represented using length bytes.  An OverflowError is
        raised if the integer is not representable with the given number of
        bytes.
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument determines whether two's complement is
        used to represent the integer.  If signed is False and a negative integer
        is given, an OverflowError is raised.
        """
        pass

    def __abs__(self, *args, **kwargs): # real signature unknown
        """ abs(self) """
        pass

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass

    def __and__(self, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass

    def __bool__(self, *args, **kwargs): # real signature unknown
        """ self != 0 """
        pass

    def __ceil__(self, *args, **kwargs): # real signature unknown
        """ Ceiling of an Integral returns itself. """
        pass

    def __divmod__(self, *args, **kwargs): # real signature unknown
        """ Return divmod(self, value). """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __float__(self, *args, **kwargs): # real signature unknown
        """ float(self) """
        pass

    def __floordiv__(self, *args, **kwargs): # real signature unknown
        """ Return self//value. """
        pass

    def __floor__(self, *args, **kwargs): # real signature unknown
        """ Flooring an Integral returns itself. """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __index__(self, *args, **kwargs): # real signature unknown
        """ Return self converted to an integer, if self is suitable for use as an index into a list. """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """
        int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        # (copied from class doc)
        """
        pass

    def __int__(self, *args, **kwargs): # real signature unknown
        """ int(self) """
        pass

    def __invert__(self, *args, **kwargs): # real signature unknown
        """ ~self """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lshift__(self, *args, **kwargs): # real signature unknown
        """ Return self<<value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mod__(self, *args, **kwargs): # real signature unknown
        """ Return self%value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

    def __neg__(self, *args, **kwargs): # real signature unknown
        """ -self """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass

    def __pos__(self, *args, **kwargs): # real signature unknown
        """ +self """
        pass

    def __pow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(self, value, mod). """
        pass

    def __radd__(self, *args, **kwargs): # real signature unknown
        """ Return value+self. """
        pass

    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass

    def __rdivmod__(self, *args, **kwargs): # real signature unknown
        """ Return divmod(value, self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __rfloordiv__(self, *args, **kwargs): # real signature unknown
        """ Return value//self. """
        pass

    def __rlshift__(self, *args, **kwargs): # real signature unknown
        """ Return value<<self. """
        pass

    def __rmod__(self, *args, **kwargs): # real signature unknown
        """ Return value%self. """
        pass

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return value*self. """
        pass

    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass

    def __round__(self, *args, **kwargs): # real signature unknown
        """
        Rounding an Integral returns itself.
        Rounding with an ndigits argument also returns an integer.
        """
        pass

    def __rpow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(value, self, mod). """
        pass

    def __rrshift__(self, *args, **kwargs): # real signature unknown
        """ Return value>>self. """
        pass

    def __rshift__(self, *args, **kwargs): # real signature unknown
        """ Return self>>value. """
        pass

    def __rsub__(self, *args, **kwargs): # real signature unknown
        """ Return value-self. """
        pass

    def __rtruediv__(self, *args, **kwargs): # real signature unknown
        """ Return value/self. """
        pass

    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass

    def __sizeof__(self, *args, **kwargs): # real signature unknown
        """ Returns size in memory, in bytes """
        pass

    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self). """
        pass

    def __sub__(self, *args, **kwargs): # real signature unknown
        """ Return self-value. """
        pass

    def __truediv__(self, *args, **kwargs): # real signature unknown
        """ Return self/value. """
        pass

    def __trunc__(self, *args, **kwargs): # real signature unknown
        """ Truncating an Integral returns itself. """
        pass

    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the real part of a complex number"""
int(x=0) -> integer
int(x, base=10) -> integer



### Python 中 `self` 关键字的作用与使用场景 #### 1. 基本概念 在 Python 的面向对象编程中,`self` 是一个约定俗成的关键字名称,用于指代类的实例本身。尽管它并不是真正的 Python 关键字[^3],但在定义类的方法时通常被用作第一个参数来表示当前实例。通过 `self`,可以访问该实例所拥有的属性和方法。 例如,在以下代码片段中,`self.name` 表示的是当前实例的 `name` 属性: ```python class Student: def __init__(self, name): self.name = name # 使用 self 来设置实例变量 def greet(self): print(f"Hello, my name is {self.name}") # 访问实例变量 ``` 在这里,`__init__()` 方法初始化了实例的属性,而 `greet()` 方法则利用这些属性执行操作[^1]。 --- #### 2. 继承中的作用 在继承关系中,子类可以通过覆盖父类的方法实现多态行为,或者调用父类的方法扩展功能。此时,`self` 同样起到核心作用,因为它始终指向具体的实例,无论这个实例属于哪个子类。 以下是继承的一个简单例子: ```python class Person: def __init__(self, name): self.name = name def introduce(self): print(f"My name is {self.name}") class Teacher(Person): # 子类继承自 Person def teach(self): print(f"{self.name} is teaching") # 调用了来自父类的 self.name ``` 在这个例子中,即使 `Teacher` 类没有重新定义 `introduce()` 方法,也可以通过 `self` 正常访问其父类的属性和方法[^1]。 --- #### 3. 描述符中的应用 除了常规的类方法外,`self` 还可以在更复杂的场景下发挥作用,比如描述符(Descriptor)。描述符是一种允许定制属性访问机制的对象协议,其中也经常涉及对 `self` 的引用。 假设有一个简单的描述符用来记录某个属性的读取次数: ```python class CountAccesses: def __init__(self, initial_value=None): self.value = initial_value self.access_count = 0 def __get__(self, instance, owner): if instance is None: return self self.access_count += 1 return self.value class MyClass: attr = CountAccesses(42) obj = MyClass() print(obj.attr) # 输出 42 并增加计数器 print(obj.attr) # 再次输出 42 和新的计数值 ``` 这里,`CountAccesses.__get__()` 方法接收三个参数:`self`, `instance`, 和 `owner`。其中,`self` 指向描述符本身的实例,而不是拥有此属性的外部类实例。 --- #### 4. 静态方法与类方法的区别 需要注意的是,并不是所有的类方法都需要 `self` 参数。对于那些不依赖于具体实例而是针对整个类的操作,则应分别使用静态方法 (`@staticmethod`) 或者类方法 (`@classmethod`)。 - **静态方法**: 不需要任何特殊的首个参数。 ```python class MathUtils: @staticmethod def add(a, b): return a + b result = MathUtils.add(5, 7) ``` - **类方法**: 接收的第一个隐含参数是类本身,一般命名为 `cls`。 ```python class Date: @classmethod def from_string(cls, date_str): day, month, year = map(int, date_str.split('-')) return cls(day, month, year) ``` 这两种情况下都不需要用到 `self`,因为它们并不关联到特定的实例。 --- #### 总结 综上所述,虽然 `self` 并非严格意义上的关键字,但它在整个 Python 面向对象体系结构里扮演着极其重要的角色。无论是基本的数据封装还是高级的设计模式,都离不开这一简洁却强大的工具支持。 --- 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值