Hướng dẫn python get type by string - python nhận loại bằng chuỗi

6

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.

Vì vậy, tôi cần đúc một giá trị thành một loại đã cho:

if 'int' == type_name:
    value = int(value)
elif 'str' == type_name:
    value = str(value)
...

Có cách nào để làm điều đó một cách chung chung không? Ví dụ.:

type_instance = get_type_instance(type_name)
value = type_instance(value)

Tôi đang sử dụng Python 2.7, nhưng cũng sẽ quan tâm đến giải pháp Python 3.x.

Update:

Đây là giải pháp tôi đang sử dụng:

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe

Đây chỉ là một trình phân tích cú pháp đồ chơi. Đừng sử dụng trong sản xuất!Don't use in production!

Khi được hỏi ngày 29 tháng 8 năm 2012 lúc 13:05Aug 29, 2012 at 13:05

Hướng dẫn python get type by string - python nhận loại bằng chuỗi

Scribuscripuscribu

2.9304 Huy hiệu vàng32 Huy hiệu bạc43 Huy hiệu Đồng4 gold badges32 silver badges43 bronze badges

Nếu bạn chỉ cần

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
0 loại bạn có thể làm

value = getattr(__builtins__, type_name)(value)

Đã trả lời ngày 29 tháng 8 năm 2012 lúc 13:09Aug 29, 2012 at 13:09

Hướng dẫn python get type by string - python nhận loại bằng chuỗi

9

Xây dựng một dict

TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)

Đã trả lời ngày 29 tháng 8 năm 2012 lúc 13:08Aug 29, 2012 at 13:08

1

Vì bạn đã chỉ định

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
1 trong phiên bản trước của câu hỏi, tôi cho rằng bạn cũng quan tâm đến việc nhận các loại numpy. Nếu vậy, chức năng sau sẽ giải quyết điều này:

def can_typecast(type, value):        
    try:
        tp = getattr(__builtins__, type)
    except AttributeError:
        try:
            np = __import__('numpy')
            tp = getattr(np, type)
            if not isinstance(tp, type):
                raise ValueError('type string is not a type')
        except AttributeError:
            raise ValueError('Invalid type specified')
        except ImportError:
            raise ValueError('Numpy not found')
    try:
        tp(value)
    except ValueError:
        return False
    return True

Điều này làm trước tiên là nó trông xem liệu tên loại đã cho có thể được giải quyết thành một loại tích hợp. Nếu thất bại, có vẻ như xem tên loại có thể được tìm thấy trong Numpy hay không và nếu đó là một đối tượng loại hợp lệ và nếu vậy, hãy thử hoạt động diễn viên trên đó.

Đã trả lời ngày 15 tháng 11 năm 2017 lúc 14:02Nov 15, 2017 at 14:02

Chinmay Kanchichinmay KanchiChinmay Kanchi

60.3k22 Huy hiệu vàng86 Huy hiệu bạc113 Huy hiệu đồng22 gold badges86 silver badges113 bronze badges

Trong Python, bạn có thể nhận được, in và kiểm tra loại đối tượng (biến và nghĩa đen) với các hàm tích hợp

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 và
class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
3.

  • Chức năng tích hợp - Loại () - Python 3.7.4 Tài liệu
  • Chức năng tích hợp - isinstance () - Python 3.7.4 Tài liệu

Bài viết này mô tả các nội dung sau đây.

  • Nhận và in loại đối tượng:
    class Token:
    
        def __init__(self, type_name, value):
            self.type = type_name
            self.value = __builtins__[type_name](value) # not safe
    
    2
  • Kiểm tra loại đối tượng:
    class Token:
    
        def __init__(self, type_name, value):
            self.type = type_name
            self.value = __builtins__[type_name](value) # not safe
    
    2,
    class Token:
    
        def __init__(self, type_name, value):
            self.type = type_name
            self.value = __builtins__[type_name](value) # not safe
    
    3
    • Với
      class Token:
      
          def __init__(self, type_name, value):
              self.type = type_name
              self.value = __builtins__[type_name](value) # not safe
      
      2
    • Với
      class Token:
      
          def __init__(self, type_name, value):
              self.type = type_name
              self.value = __builtins__[type_name](value) # not safe
      
      3
    • Sự khác biệt giữa
      class Token:
      
          def __init__(self, type_name, value):
              self.type = type_name
              self.value = __builtins__[type_name](value) # not safe
      
      2 và
      class Token:
      
          def __init__(self, type_name, value):
              self.type = type_name
              self.value = __builtins__[type_name](value) # not safe
      
      3

Nhận và in loại đối tượng: class Token: def __init__(self, type_name, value): self.type = type_name self.value = __builtins__[type_name](value) # not safe 2

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 Trả về loại đối tượng. Bạn có thể sử dụng điều này để có được và in loại biến và nghĩa đen như
value = getattr(__builtins__, type_name)(value)
3 trong các ngôn ngữ lập trình khác.

print(type('string'))
# 

print(type(100))
# 

print(type([0, 1, 2]))
# 

Giá trị trả về của

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 là đối tượng
value = getattr(__builtins__, type_name)(value)
5 như
value = getattr(__builtins__, type_name)(value)
6 hoặc
value = getattr(__builtins__, type_name)(value)
7.

print(type(type('string')))
# 

print(type(str))
# 

Kiểm tra loại đối tượng: class Token: def __init__(self, type_name, value): self.type = type_name self.value = __builtins__[type_name](value) # not safe 2, class Token: def __init__(self, type_name, value): self.type = type_name self.value = __builtins__[type_name](value) # not safe 3

Sử dụng

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 hoặc
class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
3 để kiểm tra xem một đối tượng có thuộc loại cụ thể hay không.

Với class Token: def __init__(self, type_name, value): self.type = type_name self.value = __builtins__[type_name](value) # not safe 2

Bằng cách so sánh giá trị trả về của

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 với bất kỳ loại nào, bạn có thể kiểm tra xem đối tượng có thuộc loại đó không.

print(type('string') is str)
# True

print(type('string') is int)
# False

def is_str(v):
    return type(v) is str

print(is_str('string'))
# True

print(is_str(100))
# False

print(is_str([0, 1, 2]))
# False

Nếu bạn muốn kiểm tra xem đó là một trong nhiều loại, hãy sử dụng

TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
4 và nhiều loại bộ dữ liệu.

  • trong toán tử trong Python (cho danh sách, chuỗi, từ điển, v.v.)

type_instance = get_type_instance(type_name)
value = type_instance(value)
0

Cũng có thể xác định các chức năng thay đổi hoạt động tùy thuộc vào loại.

type_instance = get_type_instance(type_name)
value = type_instance(value)
1

Với class Token: def __init__(self, type_name, value): self.type = type_name self.value = __builtins__[type_name](value) # not safe 3

TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
6 trả về
TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
7 Nếu đối số đầu tiên
TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
8 là một ví dụ của đối số thứ hai
value = getattr(__builtins__, type_name)(value)
5 hoặc một thể hiện của một lớp con là
value = getattr(__builtins__, type_name)(value)
5.

Bạn có thể sử dụng một tuple làm đối số thứ hai. Trả về

TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
7 nếu đó là một thể hiện của bất kỳ loại nào.

type_instance = get_type_instance(type_name)
value = type_instance(value)
2

Các chức năng tương tự như các ví dụ trên sử dụng

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 có thể được viết như sau:

type_instance = get_type_instance(type_name)
value = type_instance(value)
3

type_instance = get_type_instance(type_name)
value = type_instance(value)
4

type_instance = get_type_instance(type_name)
value = type_instance(value)
5

Sự khác biệt giữa class Token: def __init__(self, type_name, value): self.type = type_name self.value = __builtins__[type_name](value) # not safe 2 và class Token: def __init__(self, type_name, value): self.type = type_name self.value = __builtins__[type_name](value) # not safe 3

Sự khác biệt giữa

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 và
class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
3 là
class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
3 trả về
TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
7 ngay cả trong các trường hợp các lớp con kế thừa lớp được chỉ định trong đối số thứ hai.

Ví dụ, xác định các siêu lớp sau (lớp cơ sở) và lớp con (lớp dẫn xuất).

type_instance = get_type_instance(type_name)
value = type_instance(value)
6

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 chỉ trả về
TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
7 khi các loại khớp, nhưng
class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
3 trả về
TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
7 cũng cho siêu lớp.

type_instance = get_type_instance(type_name)
value = type_instance(value)
7

Ví dụ: loại Boolean

print(type('string'))
# 

print(type(100))
# 

print(type([0, 1, 2]))
# 
3 (
TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
7,
print(type('string'))
# 

print(type(100))
# 

print(type([0, 1, 2]))
# 
5) là một lớp con của
value = getattr(__builtins__, type_name)(value)
7.
class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
3 Trả về
TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)
7 cho cả
value = getattr(__builtins__, type_name)(value)
7 và
print(type('string'))
# 

print(type(100))
# 

print(type([0, 1, 2]))
# 
3 cho một đối tượng là
print(type('string'))
# 

print(type(100))
# 

print(type([0, 1, 2]))
# 
3.

type_instance = get_type_instance(type_name)
value = type_instance(value)
8

Sử dụng

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
2 Nếu bạn muốn kiểm tra loại chính xác và
class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
3 nếu bạn muốn kiểm tra với việc xem xét kế thừa.

Chức năng tích hợp

print(type(type('string')))
# 

print(type(str))
# 
4 kiểm tra xem một lớp có phải là lớp con của lớp khác hay không.

  • Chức năng tích hợp - ISSUBCLASS () - Tài liệu Python 3.9.7

type_instance = get_type_instance(type_name)
value = type_instance(value)
9

Làm thế nào để tôi tìm thấy một loại cụ thể trong Python?

Python có một hàm tích hợp gọi là SHECT () so sánh giá trị với loại đã cho.Nó là giá trị và loại đã cho phù hợp, nó sẽ trả về đúng nếu không sai.Sử dụng isInstance (), bạn có thể kiểm tra chuỗi, float, int, list, tuple, dict, set, class, v.v.isinstance(), you can test for string, float, int, list, tuple, dict, set, class, etc.

Làm thế nào để bạn tìm thấy loại biến trong một chuỗi trong Python?

Để có được loại biến trong Python, bạn có thể sử dụng hàm loại tích hợp ().use the built-in type() function.

Làm thế nào để bạn in một loại chuỗi trong Python?

Cách in một biến và một chuỗi trong Python bằng định dạng chuỗi.Bạn sử dụng định dạng chuỗi bằng cách bao gồm một tập hợp mở và đóng niềng răng xoăn, {}, ở nơi bạn muốn thêm giá trị của một biến.first_name = "john" print ("Xin chào {}, hy vọng bạn khỏe!")You use string formatting by including a set of opening and closing curly braces, {} , in the place where you want to add the value of a variable. first_name = "John" print("Hello {}, hope you're well!")

Loại () trả về trong Python là gì?

Python loại () hàm loại () hoặc trả về loại đối tượng hoặc trả về một đối tượng loại mới dựa trên các đối số được truyền.either returns the type of the object or returns a new type object based on the arguments passed.