Python 的 type(~)
方法可以返回現有對象的類型,也可以返回新類型的對象。
參數
現有對象的返回類型
1. object
| object
我們要返回其類型的對象。
返回新類型對象
1. name
| string
類名稱。成為__name__
屬性。
2. bases
| tuple
用於逐項列出基類的元組。成為__bases__
屬性。
3. dict
| dict
一個字典,是包含類主體定義的命名空間。成為__dict__
屬性。
返回值
返回值取決於以下情況:
案子 |
返回值 |
---|---|
與現有對象一起使用 |
對象的類型 |
用於創建新對象 |
新類型對象 |
例子
現有對象的類型
返回對象類型"abcdefg"
:
a = "abcdefg"
type(a)
str
返回對象類型"my_dog"
:
class Doge():
# This is the constructor for Python
def __init__(self, name, age):
self.name = name
self.age = age
my_dog = Doge("Roxas", 26)
type(my_dog)
__main__.Doge
正如我們所看到的,我們還可以返回自定義類對象的類型。
創建一個新對象
要創建具有 'Doge'
__name__
屬性的新對象:
Doge = type('Doge', (object,), dict(a=1))
print(Doge)
<class '__main__.Doge'>
上麵的代碼本質上與以下代碼相同:
class Doge:
a=1
print(Doge)
<class '__main__.Doge'>
相關用法
- Python type()用法及代碼示例
- Python type用法及代碼示例
- Python types.SimpleNamespace用法及代碼示例
- Python types.GenericAlias用法及代碼示例
- Python typing.get_type_hints用法及代碼示例
- Python typing.Concatenate用法及代碼示例
- Python typing.Optional用法及代碼示例
- Python typing.Final用法及代碼示例
- Python typing.TypedDict.__optional_keys__用法及代碼示例
- Python typing.Protocol用法及代碼示例
- Python typing.NoReturn用法及代碼示例
- Python typing.TypedDict.__total__用法及代碼示例
- Python typing.is_typeddict用法及代碼示例
- Python typing.AsyncGenerator用法及代碼示例
- Python typing.final用法及代碼示例
- Python typing.ClassVar用法及代碼示例
- Python typing.ParamSpec用法及代碼示例
- Python typing.Literal用法及代碼示例
- Python typing.overload用法及代碼示例
- Python typing.TYPE_CHECKING用法及代碼示例
- Python typing.TypedDict用法及代碼示例
- Python typing.List用法及代碼示例
- Python typing.get_origin用法及代碼示例
- Python typing.TypeGuard用法及代碼示例
- Python typing.ParamSpecKwargs用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python | type method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。