Previously, we discussed why Vyper is a game changer as it is one of the fastest growing smart contract development languages.
We also covered some basics like Pragma and Constructor. You can read it here.
Today we’ll take a deep dive into data types and how they work.
What are data types?
Data types help us organize different information in our code, just like we sort items into specific locations at home.
These types are set before the program is run. Just like a container designed for liquids is not suitable for storing solids, each variable in Vyper can only store the data type for which it was designed.
When writing code, we need to specify what data type each variable will hold - whether it's a number for calculations, text for a name, or true/false for simple decisions. These types ensure that our programs handle information correctly, preventing errors such as trying to multiply someone's name or add letters together.
Understanding data types in Vyper
- Boolean - simple true/false
Think of Boolean values ??like light switches - they can only be in two states: true or false. We use them in our code to make yes/no decisions.
<code>is_active: bool = True is_paused: bool = False # 可以翻轉(zhuǎn)布爾值 is_active = not is_active # 現(xiàn)在是 False</code>
Certain operators can be used effectively with boolean values, including not, or == and !=. This means we can use them to prove truth or falsehood.
**運算符** | **描述** |
---|---|
not x | 邏輯否定 |
x and y | 邏輯合取 |
x or y | 邏輯析取 |
x == y | 相等 |
x != y | 不相等 |
-
not x - flip true/false values ??to their opposites
is_door_locked = True
is_door_unlocked = not is_door_locked # Result: False
It's like saying "opposite" - if the door is locked, then being unlocked means it's open.
-
x and y - both conditions must be true
has_ticket = True
has_id = True
can_board_plane = has_ticket and has_id # Result: True
Just like you need a ticket and ID to board a plane, both values ??must be true for the result to be true.
-
x or y - at least one condition must be true.
has_cash = False
has_credit_card = True
can_pay = has_cash or has_credit_card # Result: True
For example, when paying, you can use cash or credit card; you need one of these to be true.
-
x == y - checks if two values ??are the same
password = "secret123"
entry = "secret123"
is_correct = password == entry # Result: True
It's like checking if two keys are the same.
-
x != y - checks if two values ??are different
expected_price = 100
actual_price = 90
price_changed = expected_price != actual_price # Result: True
This is like checking to see if something is different, such as noticing that a price is different than expected. These operators help you make logical Boolean decisions.
Numbers - Integers and their variants
When using numbers in smart contracts, Vyper provides two basic methods for handling integers: signed integers and unsigned integers. Each method has its specific purpose, and understanding their differences is critical to writing efficient and safe code.
- Signed integer
Signed integers are probably the most versatile number type in Vyper, capable of representing both positive and negative values. Think of a bank account - you can make deposits (positive numbers) and withdraw money (negative numbers). This is where signed integers shine. When you declare a variable such as age: int8 = -5, you are telling Vyper to reserve 8 bits of space, which can hold any number between -128 and 127.
<code>is_active: bool = True is_paused: bool = False # 可以翻轉(zhuǎn)布爾值 is_active = not is_active # 現(xiàn)在是 False</code>
For larger values, Vyper provides larger storage capacity. The int256 type is typically used for a large number of numerical operations and can handle larger numbers. Consider tracking a company's profit and loss: balance: int256 = 1000. This can represent a large financial move in either direction.
- Unsigned integer
Some values ??in the real world are never negative. You cannot have -3 apples or -5 users. This is where unsigned integers come into play. A statement like quantity: uint8 = 255 is perfect for inventory systems or user counting.
The uint8 type effectively uses 8 bits to store values ??between 0 and 255, making it ideal for small positive numbers.
<code>is_active: bool = True is_paused: bool = False # 可以翻轉(zhuǎn)布爾值 is_active = not is_active # 現(xiàn)在是 False</code>
The most commonly used unsigned integer in Vyper is uint256. When you write price: uint256 = 1000 you create a variable that can hold a huge positive number, perfect for the number of tokens or the wei value in an Ethereum transaction.
- Decimal
When you need to use decimal points for precise calculations
<code># 有符號整數(shù)(可以為正數(shù)或負數(shù)) age: int8 = -5 # 存儲范圍為 -128 到 127 balance: int256 = 1000 # 較大的范圍用于更大的數(shù)字</code>
- Address - for Ethereum accounts
We use addresses every day to identify locations - your home, a store or a friend's home. In the Ethereum world, addresses work similarly, but instead of pointing to a physical location, they point to digital wallets and smart contracts. Let’s explore what makes these addresses unique and how they work in Vyper.
What is an Ethereum address?
<code># 無符號整數(shù)(只有正數(shù)) quantity: uint8 = 255 # 存儲范圍為 0 到 255 price: uint256 = 1000 # 常用于存儲大型正數(shù)</code>
Think of your Ethereum address as a unique digital mailbox. Just like your home address ensures that mail reaches only you, an Ethereum address ensures that cryptocurrencies and digital assets reach their intended destination. In Vyper we use a special type called address to handle these addresses.
When you write something like:
<code>price: decimal = 19.99 # 適用于財務計算 tax_rate: decimal = 0.15</code>
You are creating a variable that can only store valid Ethereum addresses. These addresses always start with "0x" followed by 40 characters consisting of numbers (0-9) and letters (a-f).
Real world examples Let's say you are building a simple digital wallet contract. You can store the address like this:
<code>owner: address = 0x123... # 存儲錢包地址 contract: address = 0xABC...</code>
Use address Addresses in Vyper have special properties. You can check the following:
- How many Ether coins does one address hold
- Whether an address belongs to a smart contract
- The code is stored in the contract address
For example, checking the balance of an address is as simple as this:
<code>owner: address = 0x71C7656EC7ab88b098defB751B7401B5f6d8976F</code>
Addresses help us navigate the blockchain, ensuring our digital assets and interactions reach their intended destination safely and reliably.
- byte array - for raw data
In Vyper, byte arrays are used to process raw binary data. Think of them as containers for storing information that a computer can directly process. Byte arrays are particularly useful when working with files, cryptographic hashes, or binary operations.
<code># 錢包的所有者 owner: address = 0x71C7656EC7ab88b098defB751B7401B5f6d8976F # 可靠的備份地址 backup_wallet: address = 0x8626f6940E2eb28930eFb4CeF49B2d1F2C9C1199</code>
Static byte array Static byte arrays have a fixed size and cannot be changed. This makes it simple and efficient.
Example: Storing a fixed size hash Suppose you have a unique code such as a fingerprint that is always 32 bytes long. Here's how to store it in Vyper.
fixed_code: bytes32 This means bytes32 will always be 32 bytes.
Dynamic byte array
A dynamic byte array can accommodate data of different lengths if it does not exceed the maximum size. It helps in storing content like short messages.
Example: Save a short message Suppose you want to save a message, such as "Hello, World!", which can be up to 100 bytes long:
<code>is_active: bool = True is_paused: bool = False # 可以翻轉(zhuǎn)布爾值 is_active = not is_active # 現(xiàn)在是 False</code>
Okay, that’s it for today’s study. Our next article will examine more data types and understand their capabilities.
To read more of the above, check out the Vyper documentation and Vyper examples.
The above is the detailed content of Vyper Data Types (Series 2). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Dynamic programming (DP) optimizes the solution process by breaking down complex problems into simpler subproblems and storing their results to avoid repeated calculations. There are two main methods: 1. Top-down (memorization): recursively decompose the problem and use cache to store intermediate results; 2. Bottom-up (table): Iteratively build solutions from the basic situation. Suitable for scenarios where maximum/minimum values, optimal solutions or overlapping subproblems are required, such as Fibonacci sequences, backpacking problems, etc. In Python, it can be implemented through decorators or arrays, and attention should be paid to identifying recursive relationships, defining the benchmark situation, and optimizing the complexity of space.

Python's socket module is the basis of network programming, providing low-level network communication functions, suitable for building client and server applications. To set up a basic TCP server, you need to use socket.socket() to create objects, bind addresses and ports, call .listen() to listen for connections, and accept client connections through .accept(). To build a TCP client, you need to create a socket object and call .connect() to connect to the server, then use .sendall() to send data and .recv() to receive responses. To handle multiple clients, you can use 1. Threads: start a new thread every time you connect; 2. Asynchronous I/O: For example, the asyncio library can achieve non-blocking communication. Things to note

The core answer to Python list slicing is to master the [start:end:step] syntax and understand its behavior. 1. The basic format of list slicing is list[start:end:step], where start is the starting index (included), end is the end index (not included), and step is the step size; 2. Omit start by default start from 0, omit end by default to the end, omit step by default to 1; 3. Use my_list[:n] to get the first n items, and use my_list[-n:] to get the last n items; 4. Use step to skip elements, such as my_list[::2] to get even digits, and negative step values ??can invert the list; 5. Common misunderstandings include the end index not

Python's datetime module can meet basic date and time processing requirements. 1. You can get the current date and time through datetime.now(), or you can extract .date() and .time() respectively. 2. Can manually create specific date and time objects, such as datetime(year=2025, month=12, day=25, hour=18, minute=30). 3. Use .strftime() to output strings in format. Common codes include %Y, %m, %d, %H, %M, and %S; use strptime() to parse the string into a datetime object. 4. Use timedelta for date shipping

Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance

The "Hello,World!" program is the most basic example written in Python, which is used to demonstrate the basic syntax and verify that the development environment is configured correctly. 1. It is implemented through a line of code print("Hello,World!"), and after running, the specified text will be output on the console; 2. The running steps include installing Python, writing code with a text editor, saving as a .py file, and executing the file in the terminal; 3. Common errors include missing brackets or quotes, misuse of capital Print, not saving as .py format, and running environment errors; 4. Optional tools include local text editor terminal, online editor (such as replit.com)

TuplesinPythonareimmutabledatastructuresusedtostorecollectionsofitems,whereaslistsaremutable.Tuplesaredefinedwithparenthesesandcommas,supportindexing,andcannotbemodifiedaftercreation,makingthemfasterandmorememory-efficientthanlists.Usetuplesfordatain

To generate a random string, you can use Python's random and string module combination. The specific steps are: 1. Import random and string modules; 2. Define character pools such as string.ascii_letters and string.digits; 3. Set the required length; 4. Call random.choices() to generate strings. For example, the code includes importrandom and importstring, set length=10, characters=string.ascii_letters string.digits and execute ''.join(random.c
